Translate taxonomy term programmatically How can I translate a taxonomy term programmatically in drupal 8?
I found how to get the translated taxonomy term programmatically? but this is only related to d7.

In D8 you can translate entities with addTranslation().

This is an example for a taxonomy term:

$term->addTranslation($langcode, [
  'name' => 'translated term',
])->save();

You can provide values for all translatable fields in the array.


Button in multiform make it go to different steps Well I have an issue with a multiform. I have use the example files in
https://www.drupal.org/project/ms_ajax_form_example as a base for what I have to do in a Drupal 8 site.

Everything runs perfect, but I need in the first step to validate if the user selects a radio button, and depending in the selection of the radio make the user go to different steps in the form.

So I have my radio button in my first step:

$form['inquiry_type'] = array(
        '#type' => 'radios',
        '#title' => t('Is your inquiry regarding Parcels or Mail?'),
        '#default_value' => 0,
        '#options' => array(
            0 => t('Mail'),
            1 => t('Parcels'),
        ),
    );

The pre selected value of the radio is Mail, if the user leaves it like that the code will take him to the step number 2. But if the user selects Parcels the code should take him to step 3.

Here is how the instance of the class of the next button is done in the same class.

public function getButtons() {
    return [
      new StepOneNextButton(),
    ];
  }

And the build function in the StepOneNextButton class.

public function build() {
    return [
      '#type' => 'submit',
      '#value' => t('Next'),
      '#goto_step' => StepsEnum::STEP_TWO,
    ];
  }

I'm really new to Drupal and all of this has been an interesting journey. But I'm not sure how to evaluate the selection of the radio before the user clicks the button.

Hoping you guys can give me some insights of how this should be done.

This could be done with jQuery, like this:

$('#SUBMIT-ID').click(function () {
  $('.step-1-wrapper').addClass('hidden');
  $('.step-2-wrapper').removeClass('hidden');
});

Then you can show both steps from the beginning, and then hide them.

You also need to create a global css rule that makes a display none, on all hidden classes


Adding extra field on Main menu, similar to Amazon.com I'm building a new website on Drupal 7 and my client wants a menu that in addition to the menu items he be able to add html content, very similar to Amazon.com menu. Should I create a content type for my menu instead?

Your best option is to use the TB mega menu module add your html content to a block and add the block to the menu

  TB Mega Menu is developed following Drupal standards and best
  practices. Along with those must-have functions of a mega menu:
  display not just menu items but image, slideshow, video, article and
  customize any of them upon your favour...


What does the array_filter key in $form do? I'm following this tutorial on creating a settings form for a module in Drupal 8. The instructions say to implement the buildForm method of ConfigFormBase in the following way:
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $types = node_type_get_names();
    $config = $this->config('rsvplist.settings');
    $form['rsvplist_types'] = array(
      '#type' => 'checkboxes',
      '#title' => $this->t('The content types to enable RSVP collection for'),
      '#default_value' => $config->get('allowed_types'),
      '#options' => $types,
      '#description' => t('On the specified node types, an RSVP option will be available and can be enabled while that node is being edited.'),
    );

    $form['array_filter'] = array('#type' => 'value', '#value' => TRUE);

    return parent::buildForm($form, $form_state);

Everything here makes sense to me except I can't find any documentation on the role that they 'array_filter' key in the $form variable plays. What does this value do? Where is it documented?

Nice catch! It does nothing. You can safely remove it. Looks like some kind of forgotten relict.
Ah, yeah. The same pattern can be found in core's book module: BookSettingsForm.php.
And there is a 12(!) years old open issue to have it removed. [#315176] Clean-up remains of $form['array_filter'] hack with array_filter in book module


How to remove the separator between values of a multi value field in a Views result? I'm working on a D8 project. I have a webform with multiple fields and one of those is a taxonomy term. The taxonomy term consist of the title and a file upload field. The admin uploads a file in the taxonomy, and in the webform selects which file/s should be visible to the end user.

In order to display those files to the user I created a webform submission view where I get the specific field. The point is that the field might return multiple values (taxonomy terms) which are separated by comma.

How can I remove that comma? In D7 you could choose the separator in mulivalue field but now I can't find something similar.

EDIT:
The last idea was to change the output in the template file.
So in views-view-field.html.twig I try to replace the comma with space in the  output of the field.

{% set output = output|replace({(',') : (' '),}) %}

What I get is the html of the view with a lot of debug informations but the view is not rendered as it should.
I get something like <!-- THEME DEBUG --> <!-- THEME HOOK: 'webform_element_base_html' --> <!-- FILE NAME SUGGESTIONS: *

Any idea why?

Finally, I found the solution. I'm not sure if is the best, but it works.

function MY_THEME_preprocess_views_view_field(&$variables){
  $view = $variables['view'];

  if ($view->id() == 'VIEW_ID'){
    $output = str_replace(',', '', $variables['output']);
    $variables['output'] = \Drupal\views\Render\ViewsRenderPipelineMarkup::create($output);
  }
}


Getting different terms from different rows for the same node with Feeds I have a kind of weird CSV file to import. The structure is like that:

ID| TITLE| TERMS
1 | Title1 | term1
1 | Title1 | term2
2 | Title2 | term3
2 | Title2 | term1
3 | Title2 | term5

I would like to get all the terms from different lines to the same node. In the end, the node with "Title 1" will have taxonomy terms of "term1" and "term2".

If I directly run the importer, I know that only last value will be taken to the term field.

In short, I would like to get multiple terms from different rows to the same node.

Anyone have an idea?

In the end, I ended up with a custom php script placed inside the Drupal root. The script reads the csv line-by-line, checks the node if the term exists, if it doesnt exist, adds it to taxonomy term reference field table and taxonomy index table. Taxonomy nidex table is important because views, etc uses it to generate output.


Why to use [attributes] when adding class to a button inside my hook function I request somebody to please explain why I have to use ['#attributes'] when adding one or a combination of CSS class-es to the Submit button inside a search-block-form but when changing just the Text, ['#attributes'] is not required?

To change default text of the button I am writing:

function ezone_form_search_block_form_alter($&form, &$form_state, $form_id){
    $form['actions']['submit']['#value'] = t('Search now');
}

But when adding a CSS class to the same button I have to write this:

function ezone_form_search_block_form_alter(&$form, &$form_state, $form_id){
    $form['actions']['submit']['#attributes']['class'][] = 'btn btn-primary';
}

Why although value and class both are attributes of a button element, I have to do them differently? If I take out the ['#attributes'] part ($form['actions']['submit']['#class'][] = 'btn btn-primary';) button classes don't not render.

I Googled but could not find anything specific about it! It would be great if someone can put lights on this. I am a new comer at Drupal platform!

This more a theoretical question. You can see in the documentation or example code how to use the render element.

The technical background is, that each render element defines variables which you can use when building the render array. The variables of a render element are placed on the top level of the render array and prefixed with '#'.

This is an excerpt of the code which prepares the render element for rendering:

  public static function preRenderButton($element) {
    $element['#attributes']['type'] = 'submit';
    Element::setAttributes($element, array('id', 'name', 'value'));

Here you can see that #id, #name and #value are placed in the attributes by the element itself.

If you want to set other attributes, you have to place them yourself in #attibutes.


Jcarousel Images loads in list then conform to horizontal block I have a jcarousel of images on D7. On IE, the images will load in a list then once all the images are loaded. They conform to the horizontal scroll box. I've read on several articles about adding the overflow:hidden to the css and I have. It still appears to be loading in the list. How I can make the images not appear in a list prior to conforming to the horizontal box?

The site is www.jlucina.com and you can find the product scrolls on any of the product pages.

If you're setting overflow:hidden you also need to give the same element a static height, e.g.

#slideshow-wrapper{overflow:hidden;height:300px;}


How do I make a theme require Jquery (for anonymous users)? I'm creating a theme for D8 called 'herchel'.I'm trying to get this theme to require jquery on all pages (D8 doesn't load Jquery for anonymous users by default)

Looking through the what little documentation i can find on d.o in addition to the core themes, I created a file called herchel.libraries.yml

I've tried the following... all with no luck:

drupal.herchel:
version: VERSION
  dependencies:
    - core/jquery

-

drupal:
version: VERSION
  dependencies:
    - core/jquery

-

herchel:
version: VERSION
  dependencies:
    - core/jquery

Does anyone have any ideas on what I need to put in this?

I ran in to this upgrading one of my contrib themes to Drupal 8 as I wanted jquery.once for anonymous users. Here is what I did which works great:

In herchel.libraries.yml

herchel-corescripts:
  version: VERSION
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Then in your theme's herchel.theme file.

function herchel_preprocess_page(&$vars, $hook) {
  // Render the library as laid out in herchel.libraries.yml
  $libraries['#attached']['library'][] = 'herchel/herchel-corescripts';
  \Drupal::service('renderer')->renderRoot($libraries);
}

Pay mind to the indenting as well for the YML code. Though it's not really documented that well yet, you can have a look at this issue and its change log.

Replace hook_library_info() by *.libraries.yml file

Note that you also see a theoretical theme's "scripts.js" file in the code above but you may not need it. In my theme, that's what uses jquery to call custom code.

This code is probably a good reference too for the YML bits. Note that in both cases version is at the same level as dependencies.

I also made a list of Drupal 8 issues I encountered and took part in with my D8 upgrade.

Update:

I've fixed the code, we ran in to this issue: Replace #attached library array values with provider-namespaced strings

Note this:

 $libraries['#attached']['library'][] = array('herchel', 'herchel-corescripts');

vs.this

$libraries['#attached']['library'][] = 'herchel/herchel-corescripts';

I tested and the errors went away. :)


How to validate dependent fields for a content type? In one of my content types I have 1 field 'venue' with a drop down option. If I select 'venue' as 'other' from the drop down, some other fields (say 'venue address' and 'venue name') should become required fields and the node should not be saved or updated if those required fields are empty.

This is the screenshot of the rule I created.

This is my rule in Rules export format:

{ "rules_schedule_program_venue" : {
    "LABEL" : "Schedule Program venue",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--schedule_programs" : { "bundle" : "schedule_programs" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_venue" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_venue_address" } },
      { "data_is" : {
          "data" : [ "node:field-venue" ],
          "op" : "IN",
          "value" : { "value" : { "9" : "9" } }
        }
      },
      { "data_is_empty" : { "data" : [ "node:field-venue-address" ] } },
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "schedule_programs" : "schedule_programs" } }
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "address field is required",
          "type" : "error",
          "repeat" : "0"
        }
      }
    ]
  }
}

Please let me know what Rules Action I need to add to show an error message without updating or saving node.

I tried adding the Show a message on site action, but it is updating or saving the node anyway. I also tried with the Set an error on the form action, but in Data selector there isn't the field venue address.

Any other suggestion using javascript or jquery  to achieve this task is also fine.
Can anybody help me in using 'Rules Forms' module in this case?

I'm not aware of a way to get this to work using the Rules module. Because even if you use Rules Action "set a message" (of type = error) the node will still be saved. For more details on this, and/or possible work arounds, refer to my answer to "How to add a confirm dialog to node add and edit forms?".

If you really want to get this to work with Rules, a possible work around for your case might be to also use the Conditional Rules module, so that in your Rules Action you could "add a Rules Condition" (yes!) to check which option got selected for "venue". And if it is NOT "other", then within your Rules Action you set some dummy value (like "n.a."?) for "venue address" and "venue name".

Plan B

An alternative solution that you may want to experiment with (to see if it works in your case), is the Conditional Fields module. Excerpt from its project page:

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.

  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.

  You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.


How to programmatically set permissions for a custom content type created in a module? I have a module which creates a node type as part of hook_install. I want to be able to automatically set permission to authenticated users to create nodes.

I have tried the following code:

 /**
  * Implements hook_enable().
  */
function my_module_enable() {
  $permissions = array('create my_module_content_type content');
  user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}

But I receive this error.

Notice: Undefined index: create my_module_content_type content in user_role_grant_permissions() (line 3111 of ...

If I delete the two lines of code, the module installs fine. And when I run those 2 lines of code in an "execute PHP" window after install, they work as desired.

I believe hook_install should execute before hook_enable so the content type should exist when hook_enable is run. Are permissions defined later? Thoughts on how to handle this?

The problem is that the user_permission_get_modules function fails to get the permissions at the point of install (too early in the process, not all the caches have been reset). So you would have to copy the user_role_grant_permissions function to your new module, it should look something like this:

/**
 * Custom user_role_grant_permissions function
 * does the same thing as user_role_grant_permissions
 * but it can run at install time
 * @see user_role_grant_permissions
 * @param int $rid
 * @param array $permissions
 */
function _my_module_grant_permissions($rid, array $permissions = array()) {
    // this line doesn't work on install / enable hooks
    // $modules = user_permission_get_modules();
    // Grant new permissions for the role.
    foreach ($permissions as $module => $permission_list) {
    foreach ($permission_list as $name) {
        db_merge('role_permission')
        ->key(array(
            'rid' => $rid,
            'permission' => $name,
        ))
        ->fields(array(
            'module' => $module,
        ))
        ->execute();
    }
    }

    // Clear the user access cache.
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
}

This is slightly different than the user_role_grant_permissions module in that the permissions are keyed to the module, so you call it like this:

function my_module_enable(){
    $permissions = array(
        // module key
        'my_module' => array(
           // permissions in the module
           'do module things',
           'modify module things',
        ),
    );
    _my_module_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}


How can I use the MySQL FIELD() function within a SelectQuery object in Views? I want to use the MySQL FIELD() function to alter a query so that it orders a particular field on a particular order of keys.

The keys for this 'select' field are: active, under_contract, sold

I want to sort the View so that all of my results are sorted first by node.created DESC (this is simple, of course) and then push all sold nodes to the very bottom of the result.

I tried doing this first in hook_views_post_execute():

function mymodule_views_post_execute(&$view) {
  if ($view->name == 'my_view') {
    usort($view->result, function($a, $b) {
      return ($a->field_field_status[0]['raw']['value'] == 'sold') ? 1 : -1;
    });
  }
}

but quickly discovered that, since my view only shows 25 results per page, this only pushes sold nodes to the bottom of each page.

Next, I tried to use hook_views_query_alter() to add the awesome MySQL FIELD() function that I just discovered – which works to achieve my goal perfectly in MySQL - but can't be added (at least as I'm discovering) to a SelectQuery object, which Views uses to run the query:

function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view') {
    $query->orderby[0] = array(
      'field' => " FIELD(field_data_field_status.field_status_value, 'sold') ",
      'direction' => 'DESC',
  );
  }
}

How can I add a FIELD() orderby function to this query? Is there another method to push a particular filter value to the bottom of the result queue?

I got this working! I couldn't find any way to get the orderBy working in hook_views_query_alter(), so I tried to do this in the raw hook_query_alter(). In my particular situation, I couldn't get any result when I filtered against the table that Views had already joined with (I can't explain why) and so I added my own join. Voila, it works.

function mymodule_query_alter($query) {
  if ($query->hasTag('my_view_id')) {
    // Remove the current sort order.
    $order =& $query->getOrderBy();
    $order = array();

    // Join with the table that we need, giving it a custom alias.
    $query->join('field_data_field_listing_status', 'custom_status', 'custom_status.entity_id = node.nid');

    // Add our cool FIELD() function to push all 'sold' nodes to the very back of the list.
    $query->orderBy("FIELD(custom_status.field_listing_status_value, 'sold')", 'ASC');

    // Add any other ordering that we need...
    $query->orderBy('node_created', 'DESC');
  }
}


Create an 'active' class for partial url? I have a system of menus on a site that helps the user drill down to the page they are looking for.  If they click a link in the main nav, it might take the to /category.  On that page, a sidebar menu would direct them to /category/page.

Previously, I have used the active class to highlight a menu item while the user is on that page.  In this case, I want both menu items to be highlighted, since the page the user is on falls is a part of the main category.

To clarify, how can I keep a link active if it points to /category and the page the user is viewing is /category/page?

Thanks for the help!

There is a module for that - Menu Trail By Path

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1

Menu Items with these paths will get the active-trail class on them and expand accordingly.

blog
blog/category1
blog/category1/article1

This is particularly useful if you want a lot of nodes to appear as children of certain nodes / taxonomy term / views / referenced nodes / etc, but do not want to add them all to the menu. eg. hundreds of blog articles.

Menu Trail By Path is best used in conjunction with Pathauto.


How to add constraints to custom data arrays? I am validating csv files. I am thinking of using constraints and constraint validator framework available in Drupal to validate the data in the files. However, these seem to be designed to be attached to entity fields. For example.
/**
 Implements hook_entity_base_field_info_alter().
 */
 function projectname_commerce_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
   if ($entity_type->id() === 'commerce_order_item') {
     if (!empty($fields['unit_price'])) {
       $fields['unit_price']->addConstraint('PriceBelowMax');
     }
   }
 }

where PriceBelowmax is a custom constraint. I would like to attach this constraint to a custom data array. For example
myCustomValidatemethod($data_array, $constraints)

where constraints would be the list of constraints defined in Drupal both core and custom. Is there some reference for the above method.

You cannot validate generic data against a list of constraints you create.
Constraints are attached to specific typed data objects, entity fields, or entities. You can only validate them against the constraints they have, and you don't need to get first the list of the constraints that apply.
If $entity contains an entity, you can use the following code to check if it validates against its constraints.
$violations = $entity->validate();
if ($violations) {
  // The entity didn't pass validation from constraints.
  // For each validation $validation->getMessage() returns the
  // error message. $violation->getPropertyPath() returns the property
  // path for the property that failed validation, for example
  // field_text.0.value, if the validation failed for the value property of
  // field_text.
}

To validate only a single entity field, for example field_text in $entity, instead of $entity->validate(), which would validate the entity and all its entity fields, the method to call is $entity->field_text->validate().


How can I achieve this functionality? I am a new vibe drupal developer and I have created content type as an event which displays on home page upcoming event as blogs
i have created a simple blog event using view home page but I don't know how to achieve these using view or other modules. plz correct me if i am wrong thanks in advance
Expected result
when a user clicks these of any event it displays image and title description main square

image
event title

One
event description

title: 1 jan(Date)
description:event description
title: 2 jan(Date)
description:event description
title: 3 jan(Date)
description:event description

I assume you have already added the image and event description, etc. as fields for the event content type.
For custom content types, normally you control the display using the Manage Display link from Structure -> Content Types -> Edit.
You can rearrange the fields how you want in the UI, and you can also use a Twig theme template to customize the specific HTML.  Core also provides the Layout Builder module to make something more complex.
It's also possible to use Views to overwrite the default content page, but it is usually easier to use Twig templates and/or Layout Builder.  If you do want to use Views, take a look at the core Taxonomy Term display to see how Views can be used to override a path for a custom content type.


Reference Custom Field on User Profile I'm very close to getting this working right. I created a custom content type with several decimal fields and an entity reference field where you select a user to assign the content to. I am using a computed field to add up the decimal fields and would like to multiply them by a field that I've added to the User profile.

The problem is that I don't know how to reference the field.

This doesn't seem to work:

field_get_items($entity_type, $entity, 'field_percentage_split')[0]

I'm using Drupal 7. Any ideas?

Thank you!

You should expand the code in your question a little.

First you need to get the assigned uid with something like:

$assigned_uid = $node->field_assigned_user[LANGUAGE_NONE][0]['target_id'];

Then you need to load the user object:

$assigned_user = user_load($assigned_uid);

Then you have access to the value:

$percentage_split = $user->field_percentage_split[LANGUAGE_NONE][0]['value'];

To help visualize the $node and $user objects and how to access the information, you can put the print_r() function into a php-enabled block in your footer.

EDIT:

I looked at your code, and you should not try to do everything in a single statement. No wonder you are having problems. Break it out step by step like this:

// Get the assigned User ID from the node object

$assigned_uid = $node->field_assigned_user[LANGUAGE_NONE][0]['uid'];
// Load the user object for the assigned User.
$assigned_user = user_load($assigned_uid);
// Get the Percentage Split from the user object for the Assigned User (default to 0).
$percentage_split = (isset($assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'])) ? $assigned_user->field_percentage_split[LANGUAGE_NONE][0]['value'] : 0;
// Get the remaining values from the node object, defaulting to 0 if not there.
$other_ins = (isset($node->field_other_ins_[LANGUAGE_NONE][0]['value'])) ? $node->field_other_ins_[LANGUAGE_NONE][0]['value'] : 0;
$vb = (isset($node->field_vb[LANGUAGE_NONE][0]['value'])) ? $node->field_vb[LANGUAGE_NONE][0]['value'] : 0;
$finder_s_fee = (isset($node->field_finder_s_fee[LANGUAGE_NONE][0]['value'])) ? $node->field_finder_s_fee[LANGUAGE_NONE][0]['value'] : 0;
$broker_fee = (isset($node->field_broker_fee[LANGUAGE_NONE][0]['value'])) ? $node->field_broker_fee[LANGUAGE_NONE][0]['value'] : 0;
$dlc_franchise_fee_hst = (isset($node->field_dlc_franchise_fee_hst[LANGUAGE_NONE][0]['value'])) ? $node->field_dlc_franchise_fee_hst[LANGUAGE_NONE][0]['value'] : 0;

// Do the math.

$value = ($other_ins + $vb + $finder_s_fee + $broker_fee - $dlc_franchise_fee_hst ) * $percentage_split;

You also seem to be trying to use D6 data structures (won't work in D7), and it will also not work to try to give a function array keys.


How to fetch customer shipping information from rule component? I created a rule for that sends each product creator an email on the "Completing the checkout" event. The rule, component, and action all work, but I can't find the Customer Shipping Information tokens.

Can you provide insight or ideas on how I might get a token that would reveal the shipping information for my email? Below is my rule component and screenshots.

{ "rules_send_email_to_vendor" : {
"LABEL" : "Send email to vendor",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [] },
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "component_rules_fetch_product_author" : { "line_id" : [ "list-item" ] } }
      ]
    }
  }
]
}
}

And below my rules screenshoot

A couple of things, you actually have two rules:

The first is the event rule that loops through the products
The second is the component rule that fires off each email

  Interesting side note, given your setup, you will likely be sending an email per product and not per product creator.

To get the shipping address in rules when you have access to an order entity, you simply need to add a condition "Entity has field" and check that the "line-id:order" has the customer's shipping profile field (by default this condition looks like this):

Here's an animated gif displaying the process:


How to force users to choose a forum when creating new thread? Here is the problem: On a D7 community site, upgraded from D6, users are allowed to create new forum threads using node/add/forum link. In the node creation page ,they have to choose which forum their thread belongs to.

The default forum in the drop-down menu is set to '-None-' . So users who do not choose any forum, end up creating their thread in the 'None' forum, which then appears as the first forum and is obviously not desirable.

I am wondering who to get rid of this annoying problem?

Bit late, but someone else might find this useful.

My method was to use my theme template.php in D7 to modify the form:

Add an entry to the list of forums (I only had a simple, non-hierachical list) e.g.    $form['taxonomy_forums']['und']['#options']['0'] = '-choose a forum-';
Add a validation function to the form. $form['#validate'][] = 'cirqasupport_validate_forum_area';
In the validation function test the 'tid' being returned and if it was zero return an error on the forum field.

For example, add the following to template.php for your theme (or it could be done in a new module instead):

function mytheme_form_forum_node_form_alter(&$form, &$form_state){
   // force user to select a forum by putting a blank one at the top
   // and then checking that it is not what gets returned
   $form['taxonomy_forums']['und']['#options']['0'] = '-choose a forum-';
   $form['#validate'][] = 'mytheme_validate_forum_area';
}

and the validation function:

function mytheme_validate_forum_area($form, &$form_state){
   // A taxonomy_forum tid of 0 means they haven't selected one
   if ($form_state['values']['taxonomy_forums']['und'][0]['tid'] == '0')
   form_set_error('taxonomy_forums', t('You must select a forum.'));
}

The only problem I found is that the blank forum went in at the bottom of the sorted list no matter what number I gave it or how it was named.


Is it possible to use Google to find Drupal with a specific version of Drupal? Ideally it wouldn't be possible to use Google or another search engine to find many Drupal installations with e.g. Drupal core 7.31. But I'm not sure if it's not.

So I would like to know: is it in fact possible to find Drupal installations of a specific version?

Using Google Search it might be a little difficult for you. This search phrase can give you a few websites.

For better results you need some website profiler like BuiltWith to give you the list. The closest I came across was http://trends.builtwith.com/websitelist/Drupal-7 You have a list of Drupal 7 websites here but not 7.31 in particular. They might give you the details in pro-version but I have never tried.


what is the use of form[#special] in a drupal form? Now i'm working with forms and trying to add template in to it, I have form['#special'], but i don't know how to set it and what's the use of that and its usage.

You can embed anything in your form. Just add # at the beginning of the array index to indicate it's not a child element, and Form API will accept that even if it does not define or use it. Form API reference does not mention #special, so it is not an standard parameter. Instead, it's a parameter created by module's author for his own need.

For example, I usually add #machine_name to anything that can trigger AJAX, for easier handling of $form_state['triggering_element']. There are many uses.


Month and year to display based on content post date I have a magazine blog that I am creating in Drupal 7. I have the date displayed in the upper right hand corner (JAN 2012). How could I have this display work dynamically based on the post date of the article shown or current month if on the main view (blog) landing page? Each blog landing page is a view so the content is filtered that way. I two custom content types to help filter content and custom field created on each as the publish date to push and pull content based on the month. I need to use that publish date field as the date. How do I tap into that field for the date I need?

You haven't explained the context of this date. Is it representing results coming out of views like "this post was 5 days ago" or do you just want todays date on the upper right?

This will print the current date on your theme template.

<?php
echo date('Y M D');
?>

Share some more info on what this date is giving the user exactly; Drupal has some very helpful code for this kind of thing, such as format_date().


Why are values in Entites obtained directly and sometimes by using getters? For example

Drupal\Core\Entity\Entity::id() returns $this->id(or NULL)
Drupal\Core\Entity\ContentEntityBase::id() returns $this->id->value
Drupal\Core\Entity\ContentEntityBase::uuid() returns $this->get('uuid')->value
Drupal\node\Entity\Node::id() returns $this->get('nid')->value

Also in some methods there are setValue() and getValue() utilised but sometimes there are just $this->field->value.
So what is the reason for this inconsistent behavior? From my understanding all the "fields" are TypedData fields hence the setValue() and getValue() methods should be used instead of directly access $this->field->value. Besides it's strange because $value is private.

Ok, trying to answer this. This could get a bit long :)

First, to have that out of the way, Drupal\Core\Entity\Entity::id() is not TypedData relevant, only content entities (subclasses for ContentEntityBase) are typed data at the moment. So that implementation is for example used for config entities.

Now about the different methods that you mentioned.

getValue() is part of TypedDataInterface and it's not strictly defined what it returns, but it can be understood as the raw value of that typed data object. For anything that is not a so called primitive value (like a string or integer), getValue() returns an array. So if you call getValue() on the first field item of the node body ($node->body[0]), it will return array('value' => ..., 'format' => 'text_plain'). If you call it on the field item list, you get array(0 => array('value' => ..., 'format' => 'text_plain')). So for all complex data (another typed data term, it defines an objects that consists of sub-properties, like an entity or field item), think of getValue() as toArray().
Content entities no longer have public class properties. $entity->id->value goes through $entity->__get('id')->value, which is almost identical to $entity->get('id')->value, with the following differences:

get() currently only supports defined fields. _get()/_set() allow to set anything on an entity, mostly due to BC reasons, because a lot of code still sets tons of random stuff on $node. So print $node->bla works, $node->get('bla') will throw an InvalidArgumentException('Field bla is unknown.'). This could be changed if we want to.
Before PHP 5.4, $node->get('body')[1] is not supported (while $node->body1 works fine), so you have to use the rather weird $node->get('body')->offsetGet(1) (this is ArrayAccess, #2110467: Add first(), get($index) and possibly other methods to ListInterface will hopefully soon change that to a $node->get('body')->get(1)). Now that D8 will require 5.4, this isn't much of an argument anymore and the referenced issue makes it easier too.
get() is faster than __get(). On the large scale, there's not a big difference I think (other things are worse), but relatively speaking are magic method calls considerably slower than non-magic ones.

The ->value part involves more magic methods. To explain that, I first have to mention that all entity fields (including base fields like the ID) now have a fixed structure enforced: Entity : Field item list : Field item : Field properties (like value, format, target_id). If you write $entity->id->value then ContentEntityBase::__get() gives you the field item list for the id field. Then you call $field_item_list->value, which points to FieldItemList::__get() which assumes that you want to access the first field item, so it passes the call through to FieldItemBase::__get(), which then returns the value. I suggest that's enough detail for that question, if you want to know more about FieldItemBase, I'm happy to answer that in a separate question.
Now, $entity->id->getValue() and $entity->id->value are often mixed up, but they are not actually related in any way, it's just an unfortunate naming conflict. value happens to be the pseudo-standard main field property name, especially for those that only have a single value. Reference fields use target_id, and if you want to name the property of your own field type banana , then all you have to do is set it up accordingly in your FieldTypeItem::getPropertyDefinitions() implementation and it will be $entity->your_field->banana.
There are (at least) two remaining issues that will affect these API's. That is #2002134: Move TypedData metadata introspection from data objects to definition objects and #2002138: Use adapters for supporting typed data. The main goal of those combined is that entities and field items are no longer typed data objects themself but can be used as typed data through adapter classes. That in turn means that those classes do not have to respect (and poorly implement in case of entities) the TypedDataInterface/ComplexDataInterface interfaces but can define method names that make more sense in their context. For example, we can hopefully rename getValue() to toArray() or something else that has no naming conflict with value, we can rename $entity->getPropertyDefinitions() to $entity->getFieldDefinitions() and so on.

So, to come back to what your actual (I think) question is, $entity->id->value and $entity->get('id)->value are almost identical, both are currently supported, but I usually prefer and recommend get(). __get() could still change (although I consider it unlikely, as nobody is pushing there), so if you use get(), you're on the safe side I think.


How can I link to a specific comment on drupal.org? I'm aware that you can use [#1234] syntax in posts on drupal.org issue pages.

However, is there any syntax to point to the specific comment, like: [#1234:12]?

I was using it before, but I forgot the syntax and I can't find it anywhere.

References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically

That is from the very bottom of compose tips.

So just replace the colon with a hyphen and your guess would have been perfect.


Similar By Terms without vocabulary Other modules doing well but not actively developed.

How to make Similar By Terms works without vocabulary?

You might consider using Open Calais or Auto Tags to tag all your content. Open Calais will require a little configuration. It works wonderfully with Similar Terms.


How to use sdpm() or dpm()? Almost everywhere I search I find the following example for using dpm() or sdpm() with the Devel and the Search Krumo modules:

Paste the following code in your theme's template.php file, save, and clear cache.
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    sdpm($form);
  }
}

This is working fine.
But how can I see the other components, like Menu and its components or any block?
I tried following for menu but it is not working.
function mymodule_menu_link_alter(&$item, $menu) {
   sdpm($menu);
}

hook_menu_link_alter() accepts only one argument in Drupal 7. That's why your code isn't working.

Try the following:

function YOURMODULE_menu_link_alter(&$item) {
  if ($item['menu_name'] == 'YOUR_MENU') {
    dpm($item);
  }
}

I have wrapped it in an if check, since otherwise it would run dpm for all menu links on a page and depending on the amount of links it may cause memory overflow or timeout.


Services Module - 500 Internal Server Error When Accessing REST URL I created a services endpoint but any time I access the REST URL, e.g. http://www.mysite.com/endpoint I get a WSOD and the following in the firebug console:

"NetworkError: 500 Internal Server Error"

No errors in the dblog.  No errors in the apache error log.

The site is hosted on aegir.  So as a troubleshooting step I moved the entire drupal files and database to my local machine, hoping that I could step through with a debugger.  Guess what, everything works fine!

I've tried uninstalling modules one by one - no luck

I've tried with a clean drupal install on aegir - same 500 error

I'm wondering if anyone can suggest any further troubleshooting steps?

It seems that it could be something to do with the server or aegir configuration.

The problem turned out to be the PHP version on the server.  The Rest Server had a line of code that requires PHP 5.3.

There is an issue at https://drupal.org/node/2003396 and a patch at https://drupal.org/files/ServicesRESTServerFactory.inc_.patch

Installing the patch solved the problem without the need to upgrade the php version on the server


How to get drupal 7 default file upload directory? I have trouble to get the upload directroy from drupal. Is there some function returning the relative or absolute path?

This information is saved in Drupal's variables table. Use the variable_get function to get this information, passing in the name of the correct variable:

Public Filesystem Location: variable_get('file_public_path', conf_path() . '/files');
Private Filesystem Location: variable_get('file_private_path');

If you want the temporary upload directory use variable_get('file_temporary_path'); If you want to determine the system specific upload directory, regardless of the actual site configuration use the file_directory_temp function.

variable_get('file_public_path', conf_path() . '/files'); will pull the default path for you in case it has not been modified or explicitly set by the site administrator.


Some images are not displayed in IE Some images fails to load on IE.

DOM7009: Unable to decode image at URL: '[some unique url]'.

The URL are set to sites/default/files/styles/image/image_name.jpg?itok=RANDTOKEN

I can fix the error by removing the header in .htaccess

Header always set X-Content-Type-Options nosniff

But that does not seem to be a right solution. Any ideas why it behaves like this?

I'm inclined to believe this is a MIME type (or Content Type) configuration issue on the server because the "X-Content-Type-Options nosniff" would bypass this kind of problem.  That header is telling Internet Explorer to not extract MIME type info from the server response.

IE is very unforgiving these days (since IE 10 or so) with respect to the MIME type reported by the server. If your server is reporting that Jpegs are text or pngs, for example, Internet Explorer will fail to render it even if the extension is a well-known extension like "jpg."

Adding/Correcting MIME Types in Apache

You have many different ways to fix your server's reported mime type.

.htaccess (overrides server configuration)

If you're stuck with just editing your .htaccess file, add AddType image/jpeg jpeg jpg jpe to it in order to override whatever is happening with the server.

mime.types or httpd.conf (actually fixing the server configuration)

If you have full access to your server, try to locate the "mime.types" file on your server (assuming it exists) or add the "AddType" line to your httpd.conf file if jpegs aren't defined anywhere.  It's possible that the "jpg" extension or "jpeg" MIME type already exists in one of these files and is just not correctly configured.

A restart of Apache will make sure config changes are in place when you see if the problem is fixed, too.

See also

If this problem persists, there is also another question in Stack Overflow at: https://stackoverflow.com/questions/27934411/images-failing-to-load-in-ie-with-dom-7009-error-unable-to-decode-in-console that has many alternative causes.


Multiple Node Variants with Different Paths I have my node content type set up using Page Manager. I have different variants for this content type that pass different arguments to my view.  Is there any way to have these variants have different URLs? For example:

my/node/path
editors/my/node/path
retailers/my/node/path
my/node/path/anotheridentifier

The content will be different so I don't see an issue with SEO.

Try creating aliases that point to the same path (your page manager page). To create aliases go to Configuration > Search and metadata > URL aliases


Equivalent of file_transfer()? I am porting a Drupal 7 module to Drupal 8; it has a call to file_transfer($uri, $headers). What's the equivalent Drupal 8 code for this?

It seems file_transfer was removed in favor of BinaryFileResponse.

  Symfony has a Symfony\Component\HttpFoundation\BinaryFileResponse
  class that can be used to deliver files through PHP to the client. It
  also supports X-Sendfile and X-Accel-Mapping via
  BinaryFileResponse::trustXSendfileTypeHeader().

  file_transfer() has been dropped in favor of that.

  Drupal 7:

<?php return file_transfer($uri, $headers); ?>

  Drupal 8:

<?php
use Symfony\Component\HttpFoundation\BinaryFileResponse; ...
return new BinaryFileResponse($uri, 200, $headers);
?>

When looking for exact replacements and changes in D8, check the relevant api.drupal.org doc page and change records. I find it really comprehensive and has almost every change.

On a side note, I would reevaluate the module code if it happens for you to file_trasnfer() a file. Entire menu system was replaced with Symfony components and I think the odds are, you are still using the old system if it happens to file_transfer() or use some request-response thing in the site.


Unable to auto-create node from webform I attempted to create a custom module that automatically creates a node upon submission. I used the second response in this post: How to create a node out of a webform submission?

Per the instructions, I added a php file to a new custom module created through Drupal console. It has an info.yml and .module files.

I took the code from the second comment and altered to suit my module, and add dependencies. (For some reason, the dependencies were incorrect.)

My PtcWebformHandler.php file contents:

<?php

namespace Drupal\ptc_node_from_form\Plugin\WebformHandler;

use Drupal\Core\Annotation\Translation;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\webform\Annotation\WebformHandler;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\Plugin\WebformHandler\EmailWebformHandler;

/**
 * Create a new Article node from a webform submission.
 *
 * @WebformHandler(
 *   id = "add_new_company",
 *   label = @Translation("Create a node on submit"),
 *   category = @Translation("Content"),
 *   description = @Translation("Creates a new Article node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class PtcWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission)
  {
    // Get an array of form field values.
    $submission_array = $webform_submission->getData();

    // Prepare variables for use in the node.
    $title = $submission_array['subject'];

    // Create the node.
    $node = Node::create([
      'type' => 'company',
      'status' => FALSE,
      'title' => $title
    ]);

    $node->save();
  }
}

Before enabling the module, I added the email handler (the other post doesn't specifically say to, but it says a handler is required. And the code references an email array.)

After enabling the module, I submited a form, and checked for the node. And... no node.

I'm still getting used to Drupal 8 module development. I tried my hand at creating a service. But I doubt it is necessary (if I understand services). In any regard, it still doesn't create a new node upon form.  submission.

I tried to use xdebug to see what the data was being passed to the method inside the PtcWebformHandler class. It didn't hit anything.

What am I missing.

(It worked when I added the router from the first comment in the aforementioned post.)

Source: https://www.drupal.org/project/reroute_email

Do you have a node type "company" that exists?
Is the machine name correct?
Does your $title have a correct value?

You might just be missing ->enforceIsNew() but I'm not sure if that is required.

Try the below code and build further from there. (Edit the required values!!)

$newNode = Node::create([
  'type' => 'your_node_type_machine_name',
  'title' => 'the title of the new node',
]);

$newNode->enforceIsNew();
$newNode->save();

Also make sure you include

use Drupal\node\Entity\Node;

But looks like you already have that.


Get state list of a country In drupal 8 we can get country list using following code.

$countries = \Drupal::service('country_manager')->getList();

But how can I programatically get the list of state of each country?

Drupal core only keeps a record of countries, not all the states/administrative areas within each country.

However the CommerceGuys addressing library has that functionality. Example from their readme:

use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;

$subdivisionRepository = new SubdivisionRepository();

// Get the subdivisions for Brazil.
$states = $subdivisionRepository->getAll(['BR']);
foreach ($states as $state) {
    $municipalities = $state->getChildren();
}

If need to get list of states as indexed array use the function 'getList()':

$states = $subdivisionRepository->getList(['BR']);

Then if you print the $states, you will get:

Array
(
    [AC] => Acre
    [AL] => Alagoas
    [AP] => AmapÃ¡
    [AM] => Amazonas
    [BA] => Bahia
    [CE] => CearÃ¡
    [DF] => Distrito Federal
    [ES] => EspÃrito Santo
    [GO] => GoiÃ¡s
    [MA] => MaranhÃ£o
    [MT] => Mato Grosso
    [MS] => Mato Grosso do Sul
    [MG] => Minas Gerais
    [PA] => ParÃ¡
    [PB] => ParaÃba
    [PR] => ParanÃ¡
    [PE] => Pernambuco
    [PI] => PiauÃ
    [RJ] => Rio de Janeiro
    [RN] => Rio Grande do Norte
    [RS] => Rio Grande do Sul
    [RO] => RondÃ´nia
    [RR] => Roraima
    [SC] => Santa Catarina
    [SP] => SÃ£o Paulo
    [SE] => Sergipe
    [TO] => Tocantins
)


How to apply Panels layouts for CiviCRM pages For CiviCRM pages Events and Contributions that has paths of e.g.

www.site.com/civicrm/contribute/transact?reset=1&id=1
www.site.com/civicrm/event/register?id=23&reset=1

And so on.

Problem is that you need to copy paste custom .php files and folders in themes dir for each form to apply custom styling, e.g. have right side and left side columns and display custom content. E.g. left side column texts and infos, descriptions and right side column contains the registration form/payments.

I can't figure out how to do that without copying multiple folders for each form and editing it each time to match the page ID.

I'm looking at the Panels and it doesn't have CiviCRM content as nodes content type to be applied and filtered out in the panels variant and etc.

Or not possible?

Most CiviCRM forms can be accessed with the Webform CiviCRM Integration module: https://www.drupal.org/project/webform_civicrm

Though the integration currently only handles on-site payment methods for contribution forms.

You can build a webform using fields from the CiviCRM form and then use panels to arrange the page, or use Webform Layout module (https://www.drupal.org/project/webform_layout) to arrange the form elements


How to perform join with multiple columns using db_select? How to perform join with multiple columns using db_select? Any help?

Here below is the sample, which I'm looking for.

SELECT * FROM digitaliq_flds_by_node a
JOIN digitaliq_fld_category b ON
  a.fld_id = b.fld_id AND
  a.fld_collection_id = b.fld_collection_id AND
  a.fld_group_name = b.fld_group_name

You can use the following code.

$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');

$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');

$terms = $query->execute();

Calls to SelectQuery::join() (like-wise SelectQuery::leftJoin(), SelectQuery::innerJoin(), and SelectQuery::addJoin()) aren't chain-able because those methods don't return a SelectQuery object, but the actual alias used for the join. If you execute the following code, you would get an error.

$query = db_select('digitaliq_flds_by_node', 'a')
  ->fields('a')
  ->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name')
  ->execute();

Strings in PHP are not objects, and they don't define the execute() method.

To verify the code is executing the right SQL query, cast $query to a string, and print it. You will get the SQL query that would be executed from your code.

$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');
$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');
print $query;

With this code, I get the following output.

SELECT a.*
FROM
{digitaliq_flds_by_node} a
INNER JOIN {digitaliq_fld_category} b ON a.fld_id = b.fld_id AND a.fld_collection_id = b.fld_collection_id AND a.fld_group_name = b.fld_group_name


taxonomy_get_tree return only few terms i have a problem with taxonomy_get_tree().

I want to get all tags from taxonomy. Tags's vocabulary ID (vid) is 1. When I check this in database there are about 4000 terms. If I use taxonomy_get_tree(1) it returns only 150 terms.

Do anybody know what I'm doing wrong?

Thanks for every advice.

Try this on your code:  taxonomy_get_tree(1,0,NULL,TRUE)

Syntax:

taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE)

  Parameters

  $vid: Which vocabulary to generate the tree for.

  $parent: The term ID under which to generate the tree. If 0, generate
  the tree for the entire vocabulary.

  $max_depth: The number of levels of the tree to return. Leave NULL to
  return all levels.

  $load_entities: If TRUE, a full entity load will occur on the term
  objects. Otherwise they are partial objects queried directly from the
  {taxonomy_term_data} table to save execution time and memory
  consumption when listing large numbers of terms. Defaults to FALSE.


Can't log in user with Rest service i'm trying to build a Headless Drupal app with symfony, i'm stuck with login, i build a custom module for drupal 8 with four functions, (login,logout,register,login_status):

<?php

/**
 * @file
 * Contains \Drupal\remoteuser\Controller\RemoteUserController
 */

 namespace Drupal\remoteuser\Controller;

 use Drupal\Core\Controller\ControllerBase;
 use Drupal\Core\Form\FormState;
 use Drupal\Core\Entity;
 use Drupal\user\Controller;
 use Symfony\Component\HttpFoundation\JsonResponse;

class RemoteUserController extends ControllerBase
{
  public function login() {
    $form_state = (new FormState())->setValues($_POST);
    \Drupal::formBuilder()->submitForm('\Drupal\user\Form\UserLoginForm', $form_state);

    // Check for errors from the from
    if ($errors = $form_state->getErrors()) {
      // Return errors to notify the client.
      return new JsonResponse( array( 'error' => $errors ) );
    }
    else {
      // Return new user session to client.
      $uid = \Drupal::service('user.auth')->authenticate($_POST['name'], $_POST['pass']);
      $session_manager = \Drupal::service('session_manager');
      $session_id = $session_manager->getId();
      return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
    }
  }

  public function register() {
    // Validate the e-mail address first.
    if (!\Drupal::service('email.validator')->isValid($_POST['mail'])) {
      return new JsonResponse( array( 'error' => 'Invalid e-mail address' ) );
    }

    // Create password if it was not provided.
    $password = $_POST['pass'] ? $_POST['pass'] : user_password();

    /** @var \Drupal\user\Entity\User $user */
    $user = entity_create('user', array(
      'name' => $_POST['name'],
      'mail' => $_POST['mail'],
      'pass' => $password,
    ));

    // Validate the object.
    $errors = $user->validate();

    if ($errors->count() > 0) {
      // Return errors to notify the client.
      return new JsonResponse( array( 'error' => $errors->__toString() ) );
    } else {
      // Save new user
      $user->save();
      // Return new user credentials
      return new JsonResponse( array( 'user' => $user->toArray() ) );
    }
  }

  public function logout() {
    $result = user_logout();

    return new JsonResponse($result);
  }

  public function login_status() {
    $uid = \Drupal::currentUser()->id();

    $session_manager = \Drupal::service('session_manager');
    $session_id = $session_manager->getId();

    return new JsonResponse( array( 'uid' => $uid, 'session_id' => $session_id ) );
  }
}

all working great except for login !, it authenticate and returns successfully the user, but when i check with login_status, it returns an anonymous user !!. but the magic is that when i test with Postman google chrome plugin, login_status returns successfully the logged in user !!, maybe the cookies are not handled correctly in symfony !! i tried also with Drupal 7 Rest services, same problem, the user is not logged in !!

Finally, it works :D, I'll just put this answer here to help how still don't know how to login user via my custom Web Services API, i had to manage the cookies from the frontend, I use symfony, after sending a POST request to /{endpoint}/user/login, and receive the response that will look like this:

{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "token": "icfD3CNT4r4QAlEGiYmqzez0MVmsPbAowVR8HtfaD4Y",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459439836",
        "login": 1459440402,
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "roles": {
            "2": "authenticated user"
        }
    }
}

i create a cookie with (any name) and the value will be "session_name=sessid", don't forget the "=".
and finally to see if the user is logged in, you need the token and the cookie that you created, send a POST request to {endpoint}/system/connect WITH this HEADERS:

X-CSRF-Token: token from the login response
Cookie: SESS948facaca231cedd9a2a526239dcb6dc=ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q (session_name=sessid)

and voila :D, you get a response like this:

{
    "sessid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
    "session_name": "SESS948facaca231cedd9a2a526239dcb6dc",
    "user": {
        "uid": "1",
        "name": "admin",
        "mail": "contact@headless.com",
        "theme": "",
        "signature": "",
        "signature_format": null,
        "created": "1459037019",
        "access": "1459440402",
        "login": "1459440402",
        "status": "1",
        "timezone": "Europe/Paris",
        "language": "",
        "picture": "0",
        "init": "contact@headless.com",
        "data": false,
        "sid": "ZkJ26dMEQQ-K3VkE9zv2Cni2lWergSOOnPlF3jkiF-Q",
        "ssid": "",
        "hostname": "127.0.0.1",
        "timestamp": "1459440402",
        "cache": "0",
        "session": "",
        "roles": {
            "2": "authenticated user"
        }
    }
}

i hope my answer help any one how is looking for how to login users via Drupal Services.


Different prices in Shopping cart form and Shopping cart summary views in Commerce price table I have a problem with price table module that I hope you can support me on this issue. As I have some products with different prices depending on item's quantity according to the commerce price table module, everything is ok except "Shopping cart summary view" that only show base price and don't show calculated prices according to quantities. Also I have found rule "Override price with price table" in admin>configuration>rules that it seems it doesn't any effect on "Shopping cart summary view" !! . If possible pls help me on this topic and thanks in advanced for your perfect module.

For ease of reference, pls find attached file that show the price difference in "Shopping cart form" with "Shopping cart summary".

In the shopping cart summary view, are you using the
(Line items referenced by commerce_line_items) Commerce Line item: Unit price (Price) field  or (Products referenced by commerce_product) Commerce Product: Price (Price) field to output the unit price?

You should be using Commerce Line item: Unit price, this one is overridden by the Override price with price table rule


Migrate CSV source serial I am using migrate to import Commerce Products from a CSV file. The CSV file doesn't have its own serial so I am using csvrownum but that obviously won't work if there are already products -- I will be migrating constantly from the CSV files and so I need a real serial. So the big question is, how do I tell Migrate to generate its own serial? prepareRow feels too late because it seems I need to supply MigrateSQLMap a key field.

Here's a rough version of the constructor of the class:

public function __construct() {
  parent::__construct();
  $this->description = t('Test CSV');

  $columns = array(
    array('product_name', 'title'),
    array('url', 'url'),
    array('price', 'price'),
  );

  $this->source = new MigrateSourceCSV('/tmp/test.csv', $columns, array('header_rows' => 1));

  $this->destination = new MigrateDestinationCommerceProduct('commerce_product', 'product');

  $this->map = new MigrateSQLMap($this->machineName,
    array(
      'csvrownum' => array(
        'type' => 'int',
        'not null' => true,
      ),
    ),
    MigrateDestinationCommerceProduct::getKeySchema('commerce_product')
  );

  $this->addFieldMapping('product_id', 'csvrownum');
  $this->addFieldMapping('title', 'title');
  $this->addFieldMapping('field_url', 'url');
  $this->addFieldMapping('commerce_price', 'price');
}

Meanwhile I got this figured out. The second argument of MigrateSQLMap is a field => schema array and you can fill in those fields in function prepareKey($source_key, $row) as necessary, say

function prepareKey($source_key, $row) {
  $row->vendor_id = $this->vendorId;
  return parent::prepareKey($source_key, $row);
}

Note: prepareRow is too late, you want prepareKey.


Drupal Commerce variations missing when creating content I have downloaded and installed the Commerce module.

Note 1:
I have a product which is made up of 2 changeable parameters e.g. say size and colour... depending upon the size and colour chosen the user will be presented with a price... Currently, this leads to a potential 18 combinations all with unique prices.

Note 2:
I have created a product content type e.g. T shirt

Note 3:
I have created 18 products with unique SKU codes for each of the possible combinations and associated prices (of the product type created in Note 2)

Note 4:
I have created a standard content type (under structure - which is intended to be used to show the product as a piece of content e.g. admin>structure>content type).  The field holding the product is of type "Product Reference" and the product reference fields, field setting is set to unlimited

Note 5:
The content type is configured to allow the user to select the 18 different variants (created in Note 3) of the product type created in note 2.

Note 6:
The content node of the type created in Note 4 works by showing the product and changes the price depending upon what the user selects from the two options e.g. size and colour

The issue:
In the content type created in Note 4 (e.g. the content node) it only shows the last 10 products created (of the product type created in Note 2) rather than showing the required 18 products... how do you get to see the other 8 product variations so that they can be selected and show up in the content node in order that those combinations may be selected?

Anyone else experience this issue?  And found a solution to it?

It looks like the widget in the content creation gui only lists up to 10 items - so I'm only seeing the last 10 items created but how to I also see the addition 8 items created.

Upgrade to Commerce 1.14. This is a well-known issue with an artificial options list introduced in prior versions. While you're at it, make sure you're running the latest version of Drupal core and taken care of any security releases, too.


Move Acquia dev destop sites to another local enviroment What would be the easiest way to move all websites from my old Mac to new Mac or Pc that are done in Acquia Dev Desktop ?

Also, downloading new version just overwrites old installation leaving websites in place, or it will create new version of DevDektop where i have to import all sites from old one ?

(Just saw your comment that you are not using Acquia Cloud so I'm editing my answer.)

Copy the current location of your local sites to your new computer.
Download the latest version of Dev Desktop.
Click on the plus sign at the lower left side of the Acquia Dev Desktop window and select Import local drupal site. In the following dialog, select Change... in the top right corner and select the root folder of your site.

FWIW: The default location of dev-desktop sites is:

  ~/Sites/devdesktop/(site root folder)

You may want to keep this convention for convenience/clarity's sake

I seem to remember having to import my sites individually after upgrading my Acquia Dev Desktop. As you can see from the above, it's really easy.


How to timestamp last block access to profile cck field I need to log when a user last accessed particular areas of my site (a content type and some views pages), to do this I have added a block using PHP filter with the below code. This block is only visible on the required pages so I was hoping it would mean when a user accesses these pages it updates the users profile with the timestamp.

global $user;
$uid = $user->uid;
$node = content_profile_load(profile,$uid);
$pid = $node->nid;
$node = node_load($pid);
$changeLastAccess = mktime();
$node->field_changes_last_access[0]['value'] = $changeLastAccess;
node_save($node);

The problem is this date always shows the CURRENT time, not the time when a user was last on one of the pages on which the block is active. I am totally stumped...

EDIT:
This was working all along, i had created the wrong CCK field type of "Date" rather than "Datestamp", changed this over and it works fine.

The above works fine, however the cck field type needs to be a "Datestamp"


use an inline javascript function (not jquery) on drupal 7 This is how jQuery is included in d7

(function ($) {
  // jquey codes here
})(jQuery);

How i can include javascript code (not jquery) in d7?

If you want to write a plain JavaScript instead of JQuery, You can proceed with normal function declaration like

function sample() {
}

and go ahead. It is normal way of the doing things in javascript, More over jQuery is a framework of javascript and as said you can add js files in the traditional way

drupal_add_js()


t() function doesn't translate strings inside node fields I built a rule using rules module to create a node of a certain content type which inserts a text of full_html format inside a body field when follow flag is flagged. This is the rule

$values = array(
        'type' => 'notification',
        'uid' => UID_OF_A_USER,
        'status' => 0,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'en'
);
$entity = entity_create ('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$url = "PROFILE_URL_OF_A_USER";
$uname = "USERNAME_OF_A_USER";
$link = l("$uname","$url");
$body_content = t("!link started following you.",array('!link' => $link));
$ewrapper->field_body->set(array('value' => $my_body_content ,'format'=>'full_html') );
$ewrapper->save();

When a user uses Follow flag to follow another user, a message is sent to the followed user which says, !link started following you.

This rule works perfectly but the problem is with translation of the !link started following you.. My website supports three languages. This is the problem:

If a user (flagging user) flags another user using Follow flag and he is in a certain language, say french, The above message in french language will be sent to the followed user, no matter in what language the followed user is viewing his profile, he will see this message in french language and by switching language it will not be translated.

I need this message to be translated in the current language of flagged user when he is viewing its profile but the message is sent in the language of the flagging user and in the profile page of the followed user will not be translated even if he switches the language.

How can I make this message translatable?

Have a look at the options you can pass on to the t() function. You can explicitly say which language you want.

So you might do something like this to handle you message content :

$to_user = get_destination_user(); // whichever way you do that...
$body_content = t("!link started following you.",
                  array('!link' => $link),
                  array('langcode' => $to_user->language ));

In essence something like the above should do it.

Also make sure that the user language is set and valid. For this you might do something like :

$to_user = get_destination_user(); // whichever way you do that...

// get destination user language if set
$message_lang = !empty($to_user->language) ? $to_user->language : '';

// check if language is defined on our site
$languages = language_list();
if (!isset($languages[$message_lang])) {
    $message_lang = '';
}
// check if the language is enabled
if (!$languages[$message_lang]->enabled) {
    $message_lang = '';
}

$body_content = t("!link started following you.",
                  array('!link' => $link),
                  array('langcode' => $message_lang ));


user cannot edit the page I have given the marketing role the 'create new', 'edit own' and 'delete own' permission for the Article content type however when I log in with that account the 'edit' button doesn't appear on the article page so that user cannot modify the page]1

Use this code may be it helpful

if ($query == $user->uid && arg(0) == 'node' && is_numeric(arg(1)) && arg(2)== 'edit' ){

$query_path= db_query("select n.nid from {node} n
where n.nid =$nid")->FetchField();
 drupal_goto('node/'.$query_path);
}

place uid with your role id


Paste field content directly to node.html.twig? The content type article has a field called field_kategorie.
It should be output in the URL in the title of the node with.

node.html.twig doesn't work as expected.

{{ field_kategorie }}{{ label }}

How to do that?

{{ node.field_test.value }} works in node.html.twig for "normal" fields, not for taxonomy fields.


How to determine reason for unprocessed files in Drupal to Drupal migration Finally ran my first file migration from Drupal 6 to Drupal 7 using UI.

3100 Items
3036 Processed
62 Unprocessed
2498 messages

I am simply trying to figure out what those 62 files are, and why they did not process.

I looked at the "messages" link for the file migration task. They all say something like:

2701   Informational   Deleted documents from index with query id:"pyli4t/file/3782" OR sm_parent_document_id:"pyl4t/file/3782" Don't know what to do with this, or how to query for unprocessed files.

I looked at the migrate_map_43b7eadb1file table for the migration task, but don't see anything that indicates what files were not processed.

I looked at the migrate_message_43b7eadb1file table and was able to locate the two files that failed using this SQL statement: SELECT * FROM migrate_message_43b7eadb1file WHERE level != 4 But, nothing about unprocessed files.

That's all I can think to do. Any suggestions?

It looks like this poster received an answer from the Drupal-to-Drupal data migration module maintainer over at drupal.org, so for convenience I will post it here:

Source:Issue#2476077: How to determine reason for unprocessed files

  Side issue first - that informational message is coming from some
  contrib module (something search-related, perhaps) and not related to
  migration per-se. Grep your codebase for "Deleted documents from
  index" to see what it might be.

  So, the unprocessed count is precisely the count of source records,
  minus the number of records in the map table (so, you will never find
  an "unprocessed" record in the map table. All processed records are
  recorded in the map table with an appropriate status.

  The first question is, are there really unprocessed records, or is the
  source count off? The most common cause of "unprocessed" records being
  reported is a malformed source query that has more than one row with
  the same primary key (fid in this case) - this can happen when joining
  to another table that has multiple rows per "base" row. Elsewhere
  you've been speaking about extending migrate_d2d classes and modifying
  their queries - could you have done that for the file query, and
  joined to another table?

  The next step is to try to identify specific unprocessed files. If
  your D6 and D7 databases are on the same MySQL server and accessible
  with the same MySQL user, you can do something like:

select d6.fid
from d6.files f
left join d7.migrate_map_myfilemigration map on f.fid=map.sourceid1
where map.sourceid1 is null

  If the dbs are not on the same server, you could try dumping the D6
  files table (or just the fids) and loading it into a temp table on the
  D7 server.


Change a field type using Migrate Can I migrate a Drupal 7 field from one field type to another using Migrate and $this->systemOfRecord = Migration::DESTINATION;?

I'm trying to move field_phone which is an ordinary Field API text field into a mobile_number field which is also a Field API field but provided by the Mobile number module.

uid is the only listed source field, and that makes sense because it's the only field selected in the query, but I don't see any examples that use JOINs to select data from fields attached to an entity.

How do I add field_phone to the source?

public function __construct($arguments) {
  $this->sourceFields['field_phone'] = t('Phone');
  parent::__construct($arguments);

  $this->systemOfRecord = Migration::DESTINATION;

  $query = db_select('users', 'u')
    ->fields('u', array('uid'))
    ->condition('uid', 0, '>');
  $this->source = new MigrateSourceSQL($query);

  $this->destination = new MigrateDestinationUser(array());

  $this->map = new MigrateSQLMap($this->machineName,
    array('uid' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'default' => 0,
      'description' => "User's {users}.uid.",
    )),
    MigrateDestinationUser::getKeySchema()
  );
  $this->addFieldMapping('uid', 'uid');
  $this->addFieldMapping('field_phone_number', 'field_phone');
}

Additionally, If I can keep the same field machine name I rather do that then moving from field_phone to field_phone_number, but it's not important.

This is hard for me to believe, but the results are telling.  The source fields were never loaded, so they weren't available to the destination handler.  I added the following prepare() function to my Migration class so that the values would be available.  I don't see any examples that look like this, so I'm almost certain there's a better way.

function prepareRow($current_row) {
  if (parent::prepareRow($current_row) === FALSE) {
    return FALSE;
  }

  $phone = db_select("field_data_field_phone", "p")
    ->fields("p", array("field_phone_value"))
    ->condition("p.entity_type", "user")
    ->condition("p.entity_id", $current_row->uid)
    ->execute()
    ->fetchField();
  $current_row->field_phone = $phone;
}


For views, how do I display only one of a series with the same title? We have a view that displays upcoming events. We use civiCRM for events. Some of our events are ongoing: they have the same title, but different dates. What logic could I use to display the next upcoming event, without displaying all upcoming events?

For instance, at the moment the events displayed are based on date. Any event that is not yet passed will display in the view. But for a class which meets 10 times, I do not want 10 of the same title, just the next class and its date/time.

To only show one immediate next upcoming event:

add Sort criteria by date (ascending so you get the events that are soonest to happen as first on the list), make sure the correct one come up top
and then limit your results to only show 1 row (Display a specified number of items to 1 under Pager options, but don't output the Pager).


Permission for translating menu items via the menu config screen I have a multi language Drupal site, Using i18n and the entity translation approach. Translating menu items from an node works well, but not all the menu items are driven by the nodes.

Now as user/1, I have permission to translate any menu item from the menu config screen:
/admin/structure/menu/manage/main-menu. I am trying to enable the same permissions for other roles/users. The second role has permissions to administer menu items and translate all entities, but for the life of me I cant figure out why the translate link doesn't show in the menu config screen for the other role. Any pointers would be greatly appreciated!

I found the answer. You have to have the following permissions set: translate interface  and administer menu items.


Check if cache is active I would like to set some functionality in a module only on if caching is turned off.

Is there a way to check in code if caching is on or off?

The "Cache pages for anonymous users" setting is stored in the variable table (as a 0 or 1), you can get it like this:

if (variable_get('cache', 0)) {
  // Cache is turned on
}

If you're interested in the "Cache blocks" setting it's also in the variables table and you can get it like this:

if (variable_get('block_cache', 0)) {
  // Block cache is turned on
}

Just for reference the first is defined in system_performance_settings() and the second in block_form_system_performance_settings_alter().


Capturing keyup event (JavaScript) from Drupal editors (CKeditor) I maintain the Textfield Counter module. An issue was raised that the module does not work for textareas with CKEditor enabled. I need to catch a keyup event from editors, or even just the CKEditor module, for the module to work. I haven't worked much with Drupal editors, nor CKEditor. Does anyone have any insight into how to do this, or an alternate solution?

Well, once again I've come up with my own answer, though it's not really the one I wanted.

First off, it does not appear that there is any Drupal JavaScript API for interacting with editors. So I had to go directly to the CKEditor API to capture the key up event.

This is the code I was eventually able to use:

CKEDITOR.on('instanceReady', function () {
  // Get the HTML ID of the textarea input that would be used if the editor were not enabled:
  var fieldID = $(".some_textarea").attr("id");
  if (CKEDITOR.instances[fieldID]) {
    // Add keyup listener.
    CKEDITOR.instances[fieldID].on("key", function () {
      // The last key pressed isn't available in editor.getData() when
      // the key is pressed. A workaround is to use setTimeout(), with no
      // time set to it, as this moves it to the end of the process queue,
      // when the last pressed key will be available.
      var editor = this;
      window.setTimeout(function () {
        var text = editor.getData();
        // Do something with the text.
        // Also note that the original textarea can be
        // retrieved from editor.element.$. So you could
        // do this:
        var originalTextarea = editor.element.$;
      });
    });
  }
});


How do I set/get third party settings on a content block? I have a content block type, and I'd like to add a couple of simple configuration options to it without setting up "real" fields. I primarily used this for instructions:

https://www.webomelette.com/drupal-8-custom-data-configuration-entities-using-thirdpartysettingsinterface

My module code:

use Drupal\block_content\Entity\BlockContent;
use Drupal\Core\Form\FormStateInterface;

function oa_blocks_form_block_content_slider_images_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $block = $form_state->getFormObject()->getEntity();

  $form['autostart'] = [
    '#type' => 'checkbox',
    '#title' => t('Autostart'),
    '#default' => $block->getThirdPartySetting('oa_blocks', 'autostart'),
  ];
  $form['#entity_builders'][] = 'oa_blocks_block_content_slider_images_form_add_form_builder';
}

function oa_blocks_block_content_slider_images_form_add_form_builder($entity_type, BlockContent $block, &$form, FormStateInterface $form_state) {
  if ($form_state->getValue('autostart')) {
    $block->setThirdPartySetting('oa_blocks', 'autostart', $form_state->getValue('autostart'));
    return;
  }
  $block->unsetThirdPartySetting('oa_blocks', 'autostart');
}

I have the following in config/schema/oa_blocks.schema.yml:

block_content.type.slider_block.third_party.oa_blocks:
  type: mapping
  label: 'Slider Block'
  mapping:
    autostart:
      type: boolean
      label: 'Autostart'

I get the following error when I try to edit the block:

Fatal error: Call to undefined method Drupal\block_content\Entity\BlockContent::getThirdPartySetting() in /Users/dicksb/Sites/devdesktop/drupal8/docroot/profiles/mogov/modules/mogov/mogov_blocks/mogov_blocks.module on line 17

What am I doing wrong?

ThirdPartySettingsInterface is used by config entitiy types:

Interface for configuration entities to store third party information.
A third party is a module that needs to store tightly coupled information to the configuration entity. For example, a module alters the node type form can use this to store its configuration so that it will be deployed with the node type.

BlockContent is a content entity type, and doesn't implement the interface, hence the error.


Wrong User Image Display - Weird Twig Cache? I'm having a weird issue with incorrect user images being displayed and it seems to be a caching issue or perhaps I am passing the user image incorrectly to my template.

Problem: If I login to a different user account I will still see the image from my account. If I rebuild the cache and then refresh the browser, I will receive the correct user image.

Am I building the user image incorrectly?

mytheme.theme

 <?php
  use Drupal\user\Entity\User;

 function gary_preprocess_block(&$variables) {
  $user = User::load(\Drupal::currentUser()->id());
  $file_uri = $user->get('user_picture')->entity->getFileUri();
  dpm($file_uri); //correct uri
  $styled_image_url = ImageStyle::load("user_pic")->buildUrl($file_uri);
  dpm($styled_image_url); //correct url
  $picture = $styled_image_url;
  $variables['user_pic'] = $picture;
 }

block--gary-account-menu.html.twig

The variables in the theme file are correct, but the output from twig when inspected, continues to give the wrong built url to the previous user image (until the cache is flushed).

I doubt I need to delete twig cache or flush caches anytime a user pic is changed or account is switched. Anyone know what I am doing wrong here?

When you add data from the current user you also have to add this cache context:

$variables['#cache']['contexts'][] = 'user';

You can also add the cache dependencies of the user, file and image style. Then modifying one of these entities will be effective immediately, see https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays


display submitted variable - where does it originate The following code appears in node.tpl.php and file_entity.tpl.php, but strangely enough not in comment.tpl.php.

  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

In node.tpl.php $display_submitted it true, but in file_entity.tpl.php it is false. I am using Zen 5.x theme.

Why is it different? I would assume it is some theme setting but I can't find it.

Where is this variable initialized? And do I just set it to true in preprocess_file_entity?

For completeness, I have added a patch to File Admin's issue queue. Patch adds the vertical tab to file entity's GUI edit page and sets the variable: 'file_submitted_' . $file_type, which is read by template_preprocess_file_entity in file_entity.module.


How to show views filters on a block or page I have a view with exposed filters to customers.

I want the exposed filters on a separate page/block and views result on a  separate page.

How to do this.

Choose exposed form in block to yes in views advanced settings, Then you can find your exposed form block in block listing page and can configure to any page or region


Dependent selects in Ctools modal I am experiencing a rather odd problem in Drupal 7.

I have a form in Ctools modal. It should contain 2 dependent select boxes (among other fields). I've done this dozen times on regular forms, but i can't make it work in the Ctools Modal form. Modal pops up, all the fields are there, all the counties are in the first select box, but it looks like it's not even reaching the ajax callback when a county is selected, so no dealer are returned. When I hard code the county id, dealers from that county show as expected.

My code is similar to the following:

menu item:

$items['modal-data/%ctools_js'] = array(
  'page callback' => 'core_modal_form',
  'page arguments' => array(1),
  'access arguments' => array('access content'),
  'delivery callback' => 'ajax_deliver',
  'type' => MENU_CALLBACK,

);

general modal handling:

function ni_core_modal_form($js) {

// Check whether js is enabled.
if ($js) {

  // Include ctools modal plugin.
  ctools_include('ajax');
  ctools_include('modal');

  // Create notify entity
  $form_state = array(
    'title' => 'Contact dealer',
    'ajax' => TRUE,
  );

  $commands = ctools_modal_form_wrapper('contact_dealer_modal_form', $form_state);

// If form was submitted.
  if (!empty($form_state['executed'])) {

    $commands[] = ajax_command_replace('#modal-content', theme_status_messages(['display' => 'status']));

  }

  print ajax_render($commands);
  drupal_exit();
 }
}

The form in ctools modal:

function contact_dealer_modal_form($form, &$form_state) {

   // get all counties
  $counties = get_dealer_counties_list();

  // Check for the selected county
  $county = isset($form_state['values']['county']) ? $form_state['values']['county'] : key($counties);

  // get dealer for selected county
  $dealers = get_dealer_select_list($county);

  $form['wrapper'] = [
    '#type' => 'container',
    '#attributes' => ['class' => ['contact-dealer-form-wrapper']],
  ];

  $form['wrapper']['county'] = [
    '#type' => 'select',
    '#title' => t('Select your county'),
    '#options' => $counties,
    '#ajax' => array(
      'callback' => '_county_dealer_callback',
      'wrapper' => 'dealer-replace',
    ),
  ];

  $form['wrapper']['dealer'] = [
    '#type' => 'select',
    '#title' => t('Select your dealer'),
    '#options' => $dealers,
    '#default_value' => 0,
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#attributes' => ['class' => ['btn btn-primary'] ],
    '#value' => t('Contact'),
  ];

  return $form;
}

ajax callback:

function _county_dealer_callback($form, &$form_state) {

  return $form['wrapper']['dealer'];
}

I will highly appreciate any suggestion!

Well, as it turns out, the problem was that the form definition was in an .inc file and Ctools couldn't find it. The solution was to simply put the form definition, submit handler and ajax callback for select in a .module file.


Configuring Drupal 6.20 to display a different icon in a specific region on a specific group of pages I've added a block called 'Course Information', configured the block to display on a particular group of pages (courses/full-time/*). This works fine, but I don't know to configure Drupal to display a different icon for each of the pages.

At present, the block contains:

<img alt="An icon symbol" src="/sites/default/files/images/icon-1.png" />

This will display the same image on each page that the block is used. How would I go about having a dynamic filename inserted, like icon-2.png, icon-3.png, icon-n.png?

If this is being displayed on nodes you can add an imagefield to the content type and set its display settings to excluded. Then make a views block that displays the image field, using a default argument of the current node.


Is it possible to change the "add new comment" text on certain content types? Is it possible to change the "add new comment" text on certain content types?  Also is it possible to only allow certain roles to post comments on this content type?

Check the roles/permission grid to restrict certain roles posting comments.

hook_node_view_alter(&$build) would help to replace the label with your custom one.

e.g.

 function MODULE_node_view_alter(&$build){
    if ( in_array($build['#node']->type, array('page')) )
    $build['links']['comment']['#links']['comment-add']['title'] = l('New Label', 'comment/reply/'. $build['#node']->nid);

There can be another easy way using String Overrides but it will not let you  do on specific content types.


Which Drupal clients allow editing of non-Blog nodes? I'm looking around at some different techniques for posting content to our heavily-customised Drupal instances.  We use a custom node type and I would like to be able to post content to that node type from a desktop client.

All of the clients I've found so far are general blogging clients - are there any available that support custom node types?  Are there any restrictions around what they can / can't do?

Depending on how much work you want to do, you could write a custom interface in HTML5/JS, then wrap it in Titanium (link below) or Air
http://www.appcelerator.com/products/titanium-desktop-application-development/

Then use the Services module http://drupal.org/project/services as the API - you might want to extend the functionality yourself

Also, not sure if this is for a particular client requirement. But if it was just node creation without opening a browser you could consider this http://drupal.org/node/1045918

...Or you can pull out the necessary code from the blog api and extend :o)

Either way I've got no simple answer I'm afraid


Making an instantiated object in a module global I am creating a Drupal 7 module, and i have a file with a class definition in it. I am able to instantiate this class successfully. Where is the best place to instantiate this class in my .module file and make that object available to my module hooks?

For instance, I don't want to do the following:

function mymod_block_view{
  $obj = new Object()
  ....
}

function mymod_block_info() {
...
$obj = new Object()
}

Normally I would just use dependency injection, but I can't add arguments to the function definitions (so far as I know)...How can I only instantiate my object once and get the members and methods of the instantiated object available to my hooks?

"Best" won't get you too far here; there are a bunch of different ways, none of them particular to Drupal, and all with advantages and disadvantages. Go with what you're comfortable maintaining.

That said, a simple singleton pattern would make most sense to me:

class MyClass {

  protected static $instance = NULL;

  protected function __construct() { }

  public static function getInstance() {
    if (!isset(static::$instance)) {
      static::$instance = new static();
    }
    return static::$instance;
  }

  // Remaining class implementation

}

// Use this as many times in a single page request to get access to the same instance of MyClass every time.
$instance = MyClass::getInstance();

I feel like I should add a bit about autoloading in Drupal 7, in case you haven't already come across the options...

Drupal 7 implements a simple autoloader; in the module's .info file you can specify the path to a file containing classes:

files[] = MyClass.php

and any class in that file will be automatically available to you anytime you want it, without having to explicitly include the file.

If you want to go one step further, check out the excellent X Autoload module. It provides a PSR-0 autoloader, which mirrors Drupal 8's autoloading.

I think PSR-4 is in the pipeline too, but that's another story...


Rules Comparison Operator Is Missing The Direct Input Method I have an "equipment" content type, which has a "manufacturer" field applied to it.  The "manufacturer" field is a taxonomy term reference to a taxonomy which contains all of the manufacturers.

When "equipment" is flagged, I want a "task" to be created.  The problem is, I need different tasks created depending on what manufacturer it is.

Task A applies to manufacturer terms 1,2, and 5.

Task B applies to manufacturer terms 3 and 4.

When I set this up in Rules, I use a "Data Comparison" to check what manufacturer the equipment belongs to.  When I use only one manufacturer, the "Data Comparison" gives me a Direct Input to compare to, I set the comparison operator to "Equals", and I can type in, for example, 2.  Everything works.

However, I want this rule to apply to manufacturers 2, 1, and 5, so I set the comparison operator to "Is One Of".  Suddenly, the Direct Input Method disappears, and I'm sunk.

Is there a way in Rules to compare if a field equals one of several taxonomy terms (OR logic)?

The key to this problem was that the data comparison was actually comparing against a field belonging to an entity that was referenced to an entity that was referenced to the entity in question.  The structure was: Task -> Ticket -> Equipment: field-manufacturer.

The solution was to specifically declare the field in Rules using "Entity has field".  In this case, I was using two entity references, so I had to use "Entity has field" once to bridge to the first entity, twice to bridge to the second entity, and a third time to identify the particular field on that entity that I wanted to compare data against.

After I set the "Entity has field" conditions in place, I was able to compare data using "is one of" and it gave me a field to type in multiple TIDs.


Render filename of file upload field in node template I have a field for uploading a file. And in *node--content_type.tpl.php* I want to just print the filename of the uploaded file.

So far I have this

$node = node_load($nid);
//get field item in correct language
$item = field_get_items('node', $node, 'field_file_upload');
//get field_file_upload value
$output1 = field_view_value('node', $node, 'field_file_upload', $item[0]);
print render($output1);

But it renders a link to the download and a thumbnail of the download type.

I want to just print out the filename. I tried using:

$output2 = field_view_value('node', $node, 'field_file_upload', $item[0]['filename']);
print render($output2);

But this renders a thumbnail of the download type e.g PDF icon rather than showing the filename.

The printed array for $output1 is:

Array
(
    [#theme] => file_link
    [#file] => stdClass Object
        (
            [fid] => 196
            [display] => 1
            [description] =>
            [uid] => 1
            [filename] => drupal-7-theming-cheat-sheet.pdf
            [uri] => public://drupal-7-theming-cheat-sheet_0.pdf
            [filemime] => application/pdf
            [filesize] => 224804
            [status] => 1
            [timestamp] => 1348746651
            [type] => undefined
            [rdf_mapping] => Array
                (
                )

        )

    [#access] => 1
)

The printed array for $output2 is:

Array
(
    [#theme] => file_link
    [#file] => stdClass Object
        (
            [scalar] => drupal-7-theming-cheat-sheet.pdf
        )

    [#access] => 1
)

Any ideas? Thanks for your help!

I think you missed a key in between. Try,

$output2 = field_view_value('node', $node, 'field_file_upload', $item[0]);
foreach ($output2 as $key) {
  if(is_object($key)) {
    echo "File Name: ".$key -> filename;
  }
}


Drupal Commerce - product attribute price based on quantity I'm here with a tricky question about Drupal Commerce.
Here's my need:

I have a group of products that have a variable price based on quantity.
Each product has specific (only for that product) attributes that can modify the price.
[The real problem] Each attribute price is variable based on the original product quantity.

A real example:
0-300 pieces -> 0.75€
300+ pieces -> 0.52€

OptionA 0-300 pieces -> 0.07€
OptionA 300+ pieces -> 0.05

So if I buy 400 pieces + OptionA i pay 0.52+0.05 each, but if I buy 200 pieces I pay 0.75+0.07.

Basically what I want to achieve is to have the attribute price dinamically changed depending on the quantity.

How could I achieve such result? I can't really find a way.
Thank you in advance!

You may decrease price by setting up the rule on "After product added to cart" event, checking up the quantity added and calculate discount in a way you want to, for example.


Importing Commerce Orders and Users I am revamping a website which is uses Drupal Commerce. I want to actually mirror the website and work on it offline before bringing it back onto the server as the newer version.

Obviously while I am doing this there is likely to be orders made and new users registered.

How can I import these or somehow bring the revamped website upto date with all users and orders?

Can anyone see any other issues with doing this also?

You can use the Commerce Migrate  and import your orders, and Feeds to import users.

From Commerce Migrate project page:

  Commerce Migrate is a general-purpose migration framework extending
  Migrate Module for bringing
  store information into Drupal
  Commerce.

Also, there is a thread about this here.