Migration into multi-value field collection I am attempting to use the patch in comment #222 of this issue (https://drupal.org/node/1175082#comment-7625869) to migrate data into a multi-value field collection.

I create an array of the objects in prepareRow() but when the migration completes and I review the nodes, only the first item in the array has populated the field collection and no subsequent items have been added. Am I missing something important?

<?php
class IngredientsMigration extends BasicMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = t('Migrate recipe ingredients from the source database into field collections.');
    $this->dependencies = array('Recipe');

    $query = Database::getConnection('default', 'legacy')
      ->select('recipes', 'r')
      ->fields('r', array('id', 'ingredients'))
        ->condition('r.id', array(2), 'IN');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationFieldCollection(
      'field_collection_ingredients',
      array('host_entity_type' => 'node')
    );

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array('type' => 'int',
          'length' => 11,
          'not null' => TRUE,
          'description' => 'Recipe ID',
          'alias' => 'r',
          ),
      ),
      MigrateDestinationFieldCollection::getKeySchema()
    );

    $this->addFieldMapping('host_entity_id', 'id')
      ->sourceMigration('Recipe')
      ->issueNumber(16);
    $this->addFieldMapping('field_ingredient_text', 'ingredients')
      ->description(t('See prepareRow method'))
      ->issueNumber(16);

    $this->addUnmigratedDestinations(array(
      'path',
      )
    );
  }

  public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $ingredients_array = preg_split('/$\R?^/m', $row->ingredients);
    $row->ingredients = array();
    foreach ($ingredients_array as $ingredient) {
      $row->ingredients[] = $ingredient;
    }
    return TRUE;
  }
}

I ended up writing a drush command to run before the migration that would take the 'ingredients' field from the source db and create a new table with the ingredients each parsed into their own row and a delta column to keep them in order. I then configured the ingredients migration to point to this table instead of the recipe table.

My DB connection for this migration ended up looking like the following:

$query = Database::getConnection('default', 'legacy')
  ->select('_recipe_ingredients', 'i')
    ->fields('i', array('id', 'recipe_id', 'ingredient'))
    ->orderBy('i.recipe_id')
    ->orderBy('i.delta');


Programmatically resize images uploaded When uploading images to D8 programmatically the setting for Maximum image resolution will be ignored and images will not be scaled down. Some of the images i have to upload are even larger then 10MB.

I am currently using this code.

$file_type = explode('.', $image)[1];
$data = file_get_contents($image);
$path = 'public://images/';

if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {

  $file = file_save_data($data, $path . md5($image) . '.' . $file_type, FILE_EXISTS_REPLACE);

  $node = Node::create(array(
    'type' => 'image',
    'title' => $image,
    'field_image' => array(
      'target_id' => $file->id(),
    ),
  ));
  $node->save();

}

I've tried to work with ImageStyle::load('max_2600x2600'), but that will only create a style in styles directory.

It would be possible to use a custom shell command but i would love to use the Drupal 8 way. How to make sure original images will get resized?

You can Use Image style before save the node.

$original_image = 'public://images/image.jpg';

// Load the image style configuration entity.
use Drupal\image\Entity\ImageStyle;
$style = ImageStyle::load('max_2600x2600');

$uri = $style->buildUri($original_image);
$url = $style->buildUrl($original_image);

Here some links may helps you

Drupal 8 - Create an Image and ImageStyle Programmatically

Drupal 8 images with image style

Flexible image style system


Adding AJAX to drupal commerce checkout pane I need to add dependable fields to Drupal Commerce checkout. I wrote my own module to do this but AJAX seems to not work.
Here is the code of my module:

function moje_panele_pane_checkout_form($form, &$form_state) {
  //parent item
  $form['sposob_dostawy'] = array(
    '#type' => 'select',
    '#title' => t('Wybierz sposób dostawy'),
    '#options' => array(
      0 => t('Kurier'),
      1 => t('Odbiór osobisty'),
    ),
    '#ajax' => array(
    'callback' => 'my_checkout_ajax_callback',
    'wrapper' => 'dane-do-odbioru',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );
  //child markup
  $form['dane_do_odbioru'] = array(
    '#title' => t("Dane do odbioru"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'markup',
  );
  //dependent field
  if ($form_state['values']['moje_panele_pane']['sposob_dostawy'] == 1) {
    $form['dane_do_odbioru'] = array(
      '#title' => t("Dane do odbioru"),
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',
    );
    $form['dane_do_odbioru']['imie'] = array(
      '#type' => 'textfield',
      '#title' => t('Imię'),
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
    );
  return $form;
}

//my AJAX callback
function my_checkout_ajax_callback($form, $form_state) {
  return $form['dane_do_odbioru'];
}

The above code works fine on normal Drupal page, but I cannot make it work on checkout page as a pane.

What am I doing wrong?

I think it might have to be related with the classes on the checkout form, if you check the commerce shipping module - it has a good ajax example on replacements - you can see how it does:

// Add a radios element to let the customer select a shipping service.
$pane_form['shipping_service'] = array(
  '#type' => 'radios',
  '#options' => $options,
  '#ajax' => array(
    'callback' => 'commerce_shipping_pane_service_details_refresh',
    'wrapper' => 'commerce-shipping-service-details',
  ),
);

And then it forces the class with a prefix:

$pane_form['service_details']['#prefix'] = '
';
$pane_form['service_details']['#suffix'] = '
';

The ajax callback is the usual one:

/**
 * Ajax callback: Returns the shipping details form elements that match the
 * currently selected shipping service.
 */
function commerce_shipping_pane_service_details_refresh($form, $form_state) {
  return $form['commerce_shipping']['service_details'];
}

So definitely possible, check the css classes you're dealing with.


Unable to programmatically render webform with supplied default values I have a block that is rendering a webform programmatically however I want to change a field based on the node that it's appearing on. I'm performing this like so.

    $webform_id = 'contact';
    $current_node = \Drupal::routeMatch()->getParameter('node');
    $contact_form = \Drupal\webform\Entity\Webform::load($webform_id);
    $values = ['data' => ['contact_email' => $current_node->field_email->value, 'message' => 'test']];
    $contact_form->getSubmissionForm($values);
    $contact_form_render = \Drupal::entityManager()
        ->getViewBuilder('webform')
        ->view($contact_form);
    return $contact_form_render;

It is able to render the webform just fine, however the supplied values for the contact_email field and the message field do not appear, even though they were supplied as a parameter for getSubmissionForm. I've used https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform as an example but I don't seem to see any discrepancies between my code and theirs.

Is there something wrong with how I'm supplying the values to the programmatically rendered webform?

UPDATE: I tried doing things in a more manual manner

$form_storage = \Drupal::entityTypeManager()->getStorage('webform');
$webform_submission = $form_storage
      ->create(['webform_id'=>'contact', 'data' => ['contact_email' => $current_node->field_email->value],'message' => 'testing']);

$contact_form_render = \Drupal::entityManager()
      ->getViewBuilder('webform')
      ->view($webform_submission);

However I get the error

  Exception: Webform id (webform_id) is required to create a webform
  submission. in Drupal\webform\Entity\WebformSubmission::preCreate()
  (line 586 of
  modules/contrib/webform/src/Entity/WebformSubmission.php).

Even though I'm explicitly setting the webform_id.

Did you try using the Webform render element documented at the bottom of https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-embed-a-webform.

return [
  '#type' => 'webform',
  '#webform' => 'your_form_id',
  '#default_data' => ['name' => 'Custom Name'],
];


How to dump a single table from database using drush? I'm aware of mysqldump utility, but is there any way of dumping a single table from database using drush (e.g. for sql-dump, sql-sync)?

You can use --tables-list option on drush command to dump specific tables.

drush sql-dump --tables-list=node,system > exportdb.sql

Above command will only make sql-dump for node and system tables.

Source


Entity Reference widget selctor in view referring same reference I searched for a solution but I didn't get it right.
Given my setup:

A content type Service, referring a content type Agency
A content type Agency
A content type Person, referring a content type Agency

Now I need to add an entity reference in Service referring some of the Persons. The list of persons needs to be limited to the persons in the same Agency (of the service).
I'm using an entity reference view to generate the list of the widget.
I tried fetching the list of the person, using contextual filter(nid) and relationship but i didn't manage to make it right.

Therefore I'm asking for help. How should I setup the view?

Thank you all

I couldn't test all the way with Entityref Views, I seem to have a bug in choosing Views on my Field settings. But I was able to create the Views and it works as expected in Views preview.

The goal is to create Views of sibling nodes. In your case we need to list Person nodes that are sibling nodes to the Service node you're currently viewing. They are sibling through the Agency Entity reference field (they both refer to the same Agency node).

When both References to Agency are the same field

This is the case when the references to Agency from both Service and Person are the same field, reused (this happens when you create one ref field on one content type, then on the other content type you choose from the second drop-down "Re-use an existing field").

Create Content Views showing Person. You don't need Page nor Block, add Entity reference Display.
Show Fields Title and Agency (to test filtering works as expected, you can remove Agency later)
Under "Entity Reference inline fields" set Separator to from (with spaces on each side) so you get meaningful output Person: Name1 from Agency: Agency1
Add a Relationship Content referenced from field_agency, you can require it. This is the Agency a Person listed in Views is referring to.
Add another Relationship Content using field_agency, set it to use the Relationship from the previous step, you can require it. This is the reverse direction, pointing to all content that is pointing to this Agency.
Add a Contextual Filter ID from Content Category and set it to use the second relationship (field_agency) and configure:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Service
Configure Entity ref field settings to use this View, and choose the widget on "Manage form display".

That's it! You can test Views through Preview by entering one of the Service NIDs. Don't forget to add some "No results" text.

The Views will list only Person that are in Agency that this Service is referring to.

When References to Agency are NOT the same field

This case is when you created two different Entity reference fields on Service and Person (they have different machine names). Configuration is a bit different even though they refer to the same Agency.

You create Views the same as above only with these differences:

The first Relationship needs to be of the Entity reference to Agency that is on the Person CT.
The second Relationship needs to be of the Entity reference to Agency that is on the Service CT.

Again this second Relationship must use the Relationship from the previous step. This is where the magic happens, where Service and Person Agency fields are compared.

The Contextual ID Filter needs to be using the second Relationship, as in the first case. This Contextual is only passing on the Service ID of the page you're on to Views.


Menu local tasks and hook preprocess I just want to remove a secondary menu local task from a preprocess function such as

function mymodule_preprocess_menu_local_tasks(&$vars, $hooks) {
    $vars['secondary'] = '';
}

I'm using D7, sky theme for front-end and seven theme for admin.
The above code works in seven but not in sky.

The sky theme page.tpl.php has a variable $secondary_local_tasks which I might be able to remove from hook_preprocess_page(). I also tried this :

function mymodule_preprocess_page(&$vars, $hooks) {
    $vars['secondary_local_tasks'] = '';
    unset($vars['tabs']['#secondary']);
}

My hook is invoked correctly, but the secondary local task is still rendered to the template. Where local tasks are prepared to be rendered after my hook ?

Finally, I've done with hook_process_page() and removed the variable secondary_local_tasks upon logged-in user role before rendering to the template.

function mymodule_process_page(&$vars, $hooks){
    global $user;
    if(array_key_exists(6, $user->roles) && arg(0) == 'user' && arg(2) == 'edit'){
        $vars['tabs']['#secondary'] = array();
        if(isset($vars['secondary_local_tasks'])){
            $vars['secondary_local_tasks'] = array();
        }
    }
}

I have also tried this from hook_preprocess_page(), but it did not work on the sky theme.
Related question is here : Profile2 and profile fields by user role


Use hook form alter to change input type I am trying to change the input type on an ubercart checkout form using hook_form_alter. I added an extra field using the uc cart extra fields pane module but there is no option to add e-mail - only text - and I need the field I added to validate as an e-mail.

The field in question is:

<input type="text" id="edit-panes-billing-address-billing-ucxf-bill-to-email" name="panes[billing][address][billing_ucxf_bill_to_email]" value="" size="32" maxlength="255" class="form-text required">

The code I am using but with no success is:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'uc-cart-checkout-form') {
    form['panes-billing-address-billing-ucxf-bill-to-email'][LANGUAGE_NONE][0]['type'] = 'email';
  }

Thanks for any assistance!

If you want alter a form via an ID check you should be using $form_id == 'uc_cart_checkout_form'. Drupal form generation functions don't use "-" characters like generated CSS id/class attributes.


How to replace a taxonomy term by its description? In drupal 7.39, I have created a taxonomy vocabulary called TYPE. Inside this vocabulary I have added list of terms called CLOSE, END and INITIAL.

By default, when I view the node page it will show the Taxonomy term as CLOSE, END. But I don't want this, instead of the CLOSE term it should be replaced with the description specified in the CLOSE term.

Any suggestions about how to do this?

You can achieve your requirement using view. In view configuration, add relationship to "Content: Taxonomy terms on node", then add "Taxonomy term: Term description (Term description)" field.


How to hide non-editable profile fields in DrupalGap? In the Drupalgap user profile there is a field that should be viewable, but not be editable by the user. I am using field permissions and the permissions are respected - the user cannot change/save/update the value.

But the field is shown in the edit view of the profile a looks editable. Is this intended?

How can I hide the field in the edit user view? Is targeting the specific field(s) individually with hook_form_alter the best way?

/**
* Implements hook_form_alter().
*/

function my_module_form_alter(form, form_state, form_id){
 try {

console.log("Form ID " + form_id); // Use to see the form id.
console.log("FORM: " + JSON.stringify(form));    // Use to inspect the form.

if (form_id == 'user_profile_form') {
   $('#edit-user-profile-form-field-points-und-0-value').css("background-color","yellow"); // not working
   $('#edit-user-profile-form-field-points').css("background-color","yellow"); //not working
   $('#edit-user-profile-form-field-points-und-0-value').hide(); //not working

// not working from: https://www.drupal.org/node/2170427:
 form.elements.edit-user-profile-form-field-points-und-0-value = {
 // type: 'textfield',
 // title: 'My Text Fied',
  options: {
    attributes: {
      disabled: 'disabled'
    }
  },
  access: false /* use this to completely hide the form element */
};

console.log("this is user_profile_form");
}
}
 catch (error) { console.log('my_module_form_alter - ' + error); }
}

During hook_form_alter() implementations in DrupalGap, the form hasn't yet been rendered into the DOM, so at that point it is not yet possible to use jQuery selectors on the form.

Instead use an inline JS event (attach it to the form's prefix or suffix during the form alter). Your inline JS page event handler can have a custom function, and that custom function can do the custom jQuery selectors. Also, that appears to be the incorrect usage of the access property. Try this instead:

// During hook_form_alter()...
form.elements['field_points'].access = false;
form.suffix += drupalgap_jqm_page_event_script_code({
    page_id: drupalgap_get_page_id(),
    jqm_page_event: 'pageshow',
    jqm_page_event_callback: 'my_user_profile_form_pageshow',
    jqm_page_event_args: JSON.stringify({
        hello: 'Hi!'
    })
});

Then make a custom function:

function my_user_profile_form_pageshow(options) {
  $('#edit-user-profile-form-field-points-und-0-value').css("background-color","yellow");
  $('#edit-user-profile-form-field-points').css("background-color","yellow");
  $('#edit-user-profile-form-field-points-und-0-value').hide();
}


Drupal6 how to hide primary navigation Is there any function like is_page(like in word press) in Drupal 6

so that I can hide primary navigation menu which is (printed using echo statement) in page.tpl.php.

My requirement is to hide navigation menu in certain pages (custom theme).

There is drupal_is_front_page

Check if the current page is the front page.

Return value

Boolean value: TRUE if the current page is the front page; FALSE if otherwise.


Cache is not updating I have 2 Drupal7 application, both is having the same code. Both application is connecting to 1 database and 1 file storage which is a separate folder/directory. My problem is when I save/edit/delete something on the other application, the other application is not updated not unless I clear its cache.
What will I do in order for the updates to reflect immediately in both application without clearing the cache?

By looking at the filecache module description:

  This module allows Drupal cache bins to be stored in files instead of
  storing in database.

This means that the data is stored in a folder and I guess this folder is not shared between your web servers.

I think you have 3 options:

(easy solution) Disable Filecache and rely on the builtin cache of drupal. This will store the bins content on your database and it will be shared/invalidated for your two servers as they share the same DB
(best solution) Replace FileCache with another caching module as Memcache or Redis. Depending on your server you might want to run those in a separate virtual machine and link them back to your web servers.
Share the folder used by FileCache across your servers.

Hope this helps.


Display users created only by the current user in Admin/People Below is the site's user access level hiearchy:

There is a user myid_administrator which has a role MYID ORGANIZATION ADMINISTRATOR. The administrator, aegono,  had enabled 'Administer users' to enable the user myid_administrator, create users.

In the url admin/people. myid_administrator can see users which has a higher level of user access than it. For example, It can see 'aegono', the administrator of the site.

I want it to display only the users , the myid_administrator created and below its user level. Is it possible ? How?
Do I have to create a customized form for the users with roles MYID ORGANIZATION ADMINISTRATOR, to add users and only see the users it created? Or is there any module than can help my problem?

Are you aware of the Subuser module? It appears to be capable of doing exactly what you want.

  This module allows users to be given the permission to create
  subusers. The subusers may then be automatically assigned a role or
  roles. The parent of the subusers then has the ability to manager the
  users they have created.


Where is $node->view set? views_preprocess_node() contains the following code.

  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = $vars['node']->view;
    $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
    if (!empty($vars['node']->view->current_display)) {
      $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;

      // If a node is being rendered in a view, and the view does not have a path,
      // prevent drupal from accidentally setting the $page variable:
      if ($vars['page'] && $vars['view_mode'] == 'full' && !$vars['view']->display_handler->has_path()) {
        $vars['page'] = FALSE;
      }
    }
  }

The part to which I am interested is the line that initializes a variable using the value of $vars['node']->view. I looked at the code executed from the Views module for a node, but I was able to find where $node->view is initialized.

Which of the node hooks (e.g. hook_node_view(), hook_node_load(), hook_node_presave()) would get a valid value for $node->view?

A quick grep of the views module points to the views_plugin_row_node_view class, whose render() function contains the following lines:

$node->view = $this->view;
$build = node_view($node, $this->options['view_mode']);

return drupal_render($build);

So when a node is rendered using the node row plugin, the view is attached to the node object immediately prior to it being passed through node_view(), which is why you see it in the theme preprocess functions.

To actually answer the question (which I missed before), hook_node_view() would get a valid view object, while the others you mentioned wouldn't (I don't think).


Drupal 7 - databases other than mysql I hear that Drupal can use not only MySQL but also Postgres, MariaDB, and MongoDB.  (Please add here if it can use also some other database.)

Which of those databases have a great enough performance gain to justify switching? And how can I switch to the proposed database?

Out of the box, Drupal supports MySQL (or an equivalent such as MariaDB), PostgreSQL and SQLite for its main database. With additional drivers it also supports Microsoft SQL server and Oracle Database.

The MongoDB module can be used to off-load storage of things like cached data, fields (ie. most data for content, user, taxonomy terms, etc.) and sessions data from the main database to MongoDB. But MongoDB alone can not be used, you still need a SQL database. See NoSQL vs Other SQL Drupal Setups and its accepted answer for more information.

I'm not an expert, but except for SQLite,  I'm not sure switching DB engine is a good way to get great performance gain. I guess each engine has its strengths and its own optimization tools. I guess great performance gains can be obtained in each of them, but you have to knows how to do it.

There are also others performance aspects to consider, such as caching layers (Varnish, Memcache, APC, etc.), clustering and Content Delivery Network for static files.


Is there any preprocess hook for date api? As I asked in above, Is there any theme preprocess hook for all of the dates that displayed in Themes Files?
I want to perform some mathematical operations on Dates that show on any content type,
Is there any solution to achieve it in my Themes Files.

Date API introduces several theme functions:

theme_date_combo
theme_date_display_combination
theme_date_display_interval
theme_date_display_range
theme_date_display_single
theme_date_text_parts

All of which can be preprocessed.

If the output you need to override isn't the result of one of those functions, you'll need to look for a different solution (e.g. depending on context you might be able to preprocess a field template).


Link tags in template file auto closing. I’m having an issue wrapping a link around some output in a template file.   I have the right template file; and I can put text like ‘start here’ and ‘end here’  and it prints out where I want the ‘a href’ tag to start and end.

However when I put in the starting ‘a href’ it auto closes.   I can put in a ‘div’ and that doesn’t auto close.   I’ve tried

  and although that html output looks right it doesn’t work either.

I’ve also used at ‘function l’ but can’t pass the $content in.

Any ideas how I can either stop the auto close, get the javascript to work or a function I can use to output the link but will except the content being passed in.

Here's my code

print '';
     print $field->content;
     print '';

The problem here was that there where links in the content being outputted.  Once I changed that the links stopped auto closing.


How can I change the "content type" field name particularly in a view? I have a few content types on my Drupal instance. Eg. case study, forum topic etc.

I have built a view, to display few nodes and their content types.

In this view, I want to display the content type as case studies instead of case study, forum topics instead of forum topic.

I don't want to change the content type globally, but I want to change the content type only in this view.

Is there any hook that I can write to make this change?

Add a field to each of your content types, let's call it "Nickname" and enter the value you want to appear in your view, ie for Case Study enter "Case Studies". Now add Nickname to your View fields, and it should output the right text for each content type.


Approach to create a custom search form for an apache solr search I am creating a search similar to the example shown below:

I am looking for the best approach to do this. My current approach is to alter the drupal default search form and add the additional elements, and then use a custom submit handler to pass the search query on to the appropriate solr search path, i.e: /search/courses/funky%20widgets.

An alternative approach would be to create the form from scratch with Form API, which may give me more flexibility, but at this stage I don't know.

It would be great to hear how others would approach this, or if there is a best practice method.

Thanks

I usually use Search API and Search API Solr. And for setting up the site layout I use Panels and Panels everywhere, so my answer will be using those modules. I'm not that familiar with Apache Solr Search but maybe it's doable with that module also. It would be interesting to hear other solutions :)

The fields you want to filter by could be built using Facet API. One thing that's pretty awesome is that the facets are shown depending on the search result. So the facet will only show filters that have results.

The tricky bit is that a facet can only be shown (as far as I know) by a query that has been run. To do this I would create a Search API view that uses you Search API index. Setup a views content pane that shows your search result. Then create a display of the type context in Views.

In your site template (setup using Panels everywhere)
Insert the view by adding a pane where you want the search result to be shown. Add your views context as a context to the panel under Contexts. Then add your facets to the region you want them to show.

Then you probably want some caching on the views context so that it doesn't fire off a query on each page load :)

Another approach as you mention would be building a custom form and redirect the user to the search page /search?q=filter or to the search page and "prefill" the facet on the search page with the filter value (ie /search?facet-argument=X).

The options in the filter list could be fetched with an entity field query so that you fetch all values for the field you want to filter by. Then cache the result of that for X min/hours so that it doesn't load your site.


Why I'm getting theme related error when trying to add external JS to form? I'm trying to add Google Map API to node form:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mm_form_node_foo_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    $form['#attached']['library'][] = 'google/maps';
}

Library config (mm.libraries.yml in module root directory):

google.maps:
  js:
    https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap: {type: external, attributes: { defer: true, async: true, data-test: map-link } } }

and the error is:

  User warning: The following theme is missing from the file system:
  google in drupal_get_filename() (line 234 of
  core/includes/bootstrap.inc).

You probably need to add the module/theme name before the attached library:

$form['#attached']['library'][] = 'mm/google.maps';

Otherwise drupal is looking for google as your module/theme name.


Taxonomy term route name? I am trying to make a custom taxonomy breadcrumbs based the code from this question:
Drupal 8 How to do a custom taxonomy breadcrumb?

This line adds a new breadcrumb for the home page:

$breadcrumb->addLink(Link::createFromRoute(t('Home'), 'front'));

PS: I removed parenthesis from front to display line here.

I want to add another breadcrumb with the text of the name of a taxonomy term and the URL of the same term:

$breadcrumb->addLink(Link::createFromRoute(t($term->getName()), $url));

I cannot figure out how to replace "front" with the route name of the $term object.

Since taxonomy terms are entities, you can simply do this:

$link = $term->toLink();
$breadcrumb->addLink($link);

As a side-note, the route name for taxonomy terms is "entity.taxonomy_term.canonical".


Show user ID in admin/people list? How difficult would it be to show a column in the user list (admin/people) that shows the user's ID number? Is this possible?

It's pretty easy if you're able to install the Administration Views module.

It replaces the default admin/people page with a view, which you can easily customise to add the user id as another column in the table.

If you're not able to use that module there are ways to do it in code, but it's a bit fiddly. I did roughly the same thing a couple of months ago (before I'd come across Admin Views) so let me know if you want me to dig the code out and post it here.


Webform Module Email - Module Specific Configuration We've built a custom web form module to handle the capturing of contact information on our website. We recently came across the Webform module and are thrilled that it has so many different customization options that we're looking to transitioning over to using it across our entire site.

Before making this move we'd like to test it out using a single form on our site that captures some user data and sends it via an email submission. This data would not be stored within the Drupal database.

Our custom form module uses the Mail System and Swift Mailer modules to handle the sending of confirmation emails and we'd like to leverage the same modules when using the Webform module.

Within the Module Specific Configuration section of the Mail System module we've defined the following:

MODULE: Webform
KEY: ccpa_email_handler
FORMATTER: Webform PHP Mailer
SENDER: Webform PHP Mailer

I assume that the KEY value needs to be associated with the ID of the Email Handler that was defined for the Webform we've put built.

Unfortunately, when using the Test feature to see what the email looks doesn't seem to be working. When I submit the form I see the inline confirmation message but the email never makes it to my inbox.

I'm sure I've got something misconfigured here but I'm grasping at what it could be. I assume it has to be something with the Mail System and Swiftmailer setup so I'm hoping someone is also using this particular type of setup and could offer some insight as far as the setup and configuration.

You say that you use Swift Mailer for your current setup, but for your test setup with Webform, it seems like you use Webform PHP Mailer.

Try to use Swift Mailer instead and see if that works.


How to insert html inside form element div I want to enhance the login form fields with icons from Font Awesome. For this I need to add some html inside the div of the name and pass fields (to be able to position accurately with css). The html part is for example something like

I tried using #suffix with hook_form_alter, but then the html is added after the div. I also tried with a user-login.tpl.php, but it seems you can only render individual form elements with drupal_render, for example drupal_render($form['name']); But this also outputs the entire div.

What I want to end up with is something like this:

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

I'm using Drupal 7.

Assuming you don't need the input wrapper. Just remove it:

$form['pass'] = array(
        '#type'             => 'password',
        '#title_display'    => 'none',
        '#maxlength'        => 128,
        '#size'             => 60,
        '#required'         => TRUE,
        '#theme_wrappers'   => array(), // remove the wrapper
        '#prefix'           => '',
        '#suffix'           => '',
        '#attributes'       => array(
                                'placeholder'   => t('Password')
                            ),
        );

the icon will be placed after the input:

<input type="password" maxlength="128" size="60" name="pass" id="edit-pass" placeholder="Password" class="inputbox form-text required">

But if you need that div wrapper, you can just rearrange his position:

$form['pass'] = array(
        '#type'             => 'password',
        '#title_display'    => 'none',
        '#maxlength'        => 128,
        '#size'             => 60,
        '#required'         => TRUE,
        '#theme_wrappers'   => array(), // remove the wrapper
        '#prefix'           => '
',
        '#suffix'           => '
',
        '#attributes'       => array(
                                'placeholder'   => t('Password')
                            ),
        );

Now the output will be exactly as you wrote:

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


Recommended module or method for a generic map/media embed field? I'm aware of lots of modules for embedding media (especially https://www.drupal.org/project/emfield) and for embedding or generating Google Maps, but what I'd like is one general purpose field in which the user can paste any valid embed code, and it will get rendered in the page. (Possibly resized, if I can dream a little.)

Is there any good module for this? Or should I build the field myself and make a template for its display? If so, how should I configure that in Drupal 7? I know how to make a template for a field in general, but my PHP is pretty shaky.

The built-in text area field seems like it would be sufficient, assuming that this field would only be accessible to trusted user types (see "Tread with Care" later in my post).  If you configure your filters to allow "Filtered HTML" (with embed/iframe allowed) or even "Full HTML",  users can just copy and paste embed codes to their heart's content.

Any HTML snippets that are posted will get rendered when viewed without needing any extra template code or a custom module to handle them.  A "Filtered HTML" filter might still strip important attributes away, but "Full HTML" will not.

There is not really a generic way I can think of that would allow you to verify (even if you felt confident about your PHP) that iframe/embed html is a Vimeo video vs a banner advertisement vs a reference to malware.  That is why there are 20 different emfield modules; the sources for each type of content all do things differently and can constantly change how they approach embedding.

Text filters are available at: /admin/config/content/formats (in Drupal 7) and full documentation can be found here: Specifying the allowed formats for user input

Tread with care!

Keep in mind that users will be able to post anything else they want, too.  The "Full HTML" filter offers minimal protection and even if you went with "Filtered HTML" instead of "Full HTML" and permitted iframe or embed tags you are still in potentially dangerous territory if this field is going to be used by just anyone in your userbase.

Example/Demonstration


Views pagers for anonymous users I've been trying to figure out why the pager element for views won't show up for anon users in Drupal 7. The following are the things I've tried to get them to show, cache clear, mess with the access param in the actual view, create a function that calls

drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');

Has anyone been able to solve this? I've searched Google for over an hour for a fix/explanation.

If after running the permission checks drupal doesn't find enough items to fill your view it will not show the pager (for any user role). You should check why there aren't enough items for the view.
Did you check for the number of items on a page (in the view). Is the pager set to be on (in the view). There are chances that you forgot to check some of these settings. It happens.


Get rid of classes from views root container Looking for a way to clear all unnecessary in terms of semantic classes from top-level div for a view:

        ROWS

want to become:

        ROWS

I have tried Semantic Views and Fences but they all deal only with view content (field or rows) but not with the top-level div config.

I know that some bits can be changed with views-view.tpl.php however you can only clear all classes from it but I want to use css class from Views configuration.

You can use template_preprocess_views_view function and remove needles classes from  $vars['classes_array'] array.

function mymodule_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view') {
    $vars['classes_array'] = array('view', $vars['css_class']);
  }
}


How to add a value to a field via custom button I was wondering how do you add a value to a field on a form(node/add) via a custom button on views?

The scenario:
On the form(node/add) a user can see and search a list of venues(view block) and on each venue there is a 'more' when clicked the user will be able to see a pop-up of the details of that certain venue. Inside the popup there is the 'Select this venue' button when clicked should be able to add that certain venue to the field 'field_choose_venue'.

I've been trying this all day but no luck. Any help will be much appreciated.

The problem is complex. I think one way to address what you want is to code a JS behavior that is attachted to your block view that when user click each venue the venue value is added to the field and add more elements button is clciked, so Drupal reconstructs the form adding a new element.

Steps:

Add the venue nid to your View but hide it using CSS. This is a quick-and.dirty way to have the Venu nid available for your JS code. A better way is to alter the views output and add the nid in some other way.
Add a JS file for your module that will be added in that add form (use form alter and the $form['#attached'] key.
Your JS file should be a Drupal behavior JS that will attach a click listener to your venues elems in the block. When clicked, the listener will have to locate the last empty venue form field element, put clicked venue nid in that field elem and click the 'Add more' button of that multiple value field to trigger and AJAX call that will make Drupal to reconstruct the form and add a new empty value for the venue form element.

But the easy way is to use Entity Reference View Widget. The behavior is not exactly what you want but I think it can fit your needs.

This module allows to open a popup with a View where you can select the values of the field. As the popup is filled woth a View you have all the power if Views to modify what user sees in the view.


How can I force administrator to provide a reason when cancelling a user account I would like to find a way for drupal site administrator to provide a reason when an account has been cancelled / blocked.

I would need a radio list such as below, then an automatic email is sent with the details of the option chosen by the admin.

Your email address is not a personal address issued by your company
E.G. a.name@yourcompany.co.uk
You did not supply your full name
You did not supply your company name
You did not supply a full address
You did not supply your telephone number

In User fields, add field of type: List Text with checkboxes radio button as widget
Use the Filed Permissions module so only admins can see this user field.
Download Rules and enable Rules UI
Create a New Rule
React on: After Updating an Existing User Account
Add Condition: Data Comparison >> account-unchanged:status >> Operator: Equals DATA Value: Blocked
Add Action >> Send Mail >> Body: [user:name] was blocked because [user:field-example]


How to edit a profile field from the node add form My client has a user field field_geolocation of type  Geofield.

And he has a content type issue, he allows people to create new issues (kinda like in drupal.org but private).

What he wants is: When someone is creating a new issue, he should be able to to set/edit the field in his profile identified by field_geolocation.

My guess: create a custom module which does the following

Inject a widget for the user field field_geolocation inside the node add/edit form, prbably with FAPI
Use Node API to save the data collected previously into the actual user.

Did I guess right? Or any better solutions?

Thank you.

You're on the right track.  It should be a pretty straight forward thing to implement.

I would add a custom submit handler to the node form for your issue content type.  Grab the submitted values for the geolocation field.  Load the user using user_load(), if the value has changed, the update it and call user_save().


how to save checkboxes values in node programmatically i want to save checkboxes values in entity reference checkboxes field with node_save
:

   $form['wrapperrr']['id_offre'] = array(
        '#title' => t('Liste des Offres'),
        '#type' => 'checkboxes',
        '#options' => $optionsoffres,

    );

and into the submit button :

$node->field_entity_reference['und'][]['value'] =$form_state['values']['wrapperrr']['id_offre'];

i found the solution
:

  $aaz= array_filter($form_state['values']['wrapperrr']['id_offre']);
 foreach($aaz as $of)
   {

  //  $node->title = $form_state['values']['wrapperrr']['id_offre'][0]['value'];
   $node->field_offre[LANGUAGE_NONE][]['target_id'] = $of;

   }


Show right node revision for View Draft, View Publised links I am using panels to override node template and on panels I am adding views blocks for the node content. I have workbench moderation enabled for this node. Issue is in showing the appropriate revision of node for workbench for example

When I use View published or View Draft link, I am seeing all revisions of node field instead of current revision for View Draft and published revision for View published.

The view I have created is on base table: node_revision and fields I am adding are Content (historical data). from panel I am passing Revision ID as context to view and in view I have contextual filter set as Content revision: Nid

Do I need to create two separate views display filtered by Workbench moderation : current and Workbench moderation : published and switch between them on basis of URL having draft or not?

Make a clone of the view that workbench itself uses, and use that as a base to work from.


Output filename in views I have an uploaded file my_cat.jpg
Upon upload, the file-entity's name is by default populated with the file's filename.

Try one: In views, adding a field file:name to my view first looks like the correct answer.
But that's the file-entity's name, which can, even after the upload, be changed to eg. My cat, while the filename on the disk will never change.

Try two: If i add a file:path field, i can decide if it should output the Download-URL or the internal Filestream-Adress.
But no way to leave out the path completely...
From the field's name, that's not a big surprise.

So, how can i get just the filesystem-filename my_cat.jpg?

In Drupal 8: in Relationships, add a relationship to your image (mine looks like: Image, (field_image:target_id), Content, Appears in: image). In the next step select "Require this relationship". Now, in Fields, you have the filename field available.


Get a node using the same category (taxonomy term) the current node is using I have two types of nodes: News and Page.
Every News node can be assigned to a category (taxonomy term), which is used also from the Page nodes.

I would like to get in a view all the News nodes that have the same category the current node has.

How can I achieve this?

Add CONTEXTUAL FILTER (Earlier arguments) on CONTEXTUAL FILTERS section on views click add, select "Content: Has taxonomy term ID" and in "WHEN THE FILTER VALUE IS NOT IN THE URL" choose Provide default value. Choose "Taxonomy ID from URL" check "Load default filter from node page, that's good for related taxonomy blocks". It will create a related taxonomy.


Drupal function to convert node into Json object I would like to know if any drupal function is readily available which converts the node object into Json object so that i can return it in the menu callback function in Ajax call.

thanks,
Ahmad

To return on menu callback function in Ajax call you can use drupal_json_output(), you can use this function as an example.

On that exampe you can see that you only need to call drupal_json_output() function with the object as the parameter, there's no need to return anything from your callback function.

If you need to convert the Drupal node object into JSON object to be returned on a function, you could consider to use drupal_json_encode()


How can I return a JSON response from an internal function ? (not the main callback) I have a callback that is running for a specific post request.
I am returning a certain JSON response at the end of it.

What if I want to catch errors inside one of the functions that are ran in that callback ? How do I get the Response object, or is there another way of sending a response immediately in case errors are catched ?

  private function someCalculation()
{

  try {

  } catch ($e) {
    //how to send response in case of error inside this function
    return new JsonResponse([
      'data' => null,
      'error' => $error
    ]);
  }
}

public function getTemplate(Request $request)
{

  $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);

}

How do I send a JSON from inside the someCalculation function in case some errors are found ?

You can do it by checking is $this->someCalculation() is instance of JsonResponse. It is is we return the response, otherwise we set $result to the calculation result.

private function someCalculation() {
  try {
    // Something.
  } catch ($e) {
    return new JsonResponse([
      'data' => NULL,
      'error' => $e->getMessage(),
    ]);
  }
}

public function getTemplate(Request $request) {
  // Alternatively you can return an array with a status code and check on that instead.
  if ($this->someCalculation() instanceof JsonResponse) {
    return $this->someCalculation();
  }
  // If it didn't fail set set $result to the calculation result.
  $result = $this->someCalculation();

  return new JsonResponse([
    'data' => $result,
  ]);
}


Form selection with radios, ajax and taxonomy terms In my form i get the message: "An illegal choice has been detected. Please contact the site administrator." after i didn't select a radio box in the 2nd form. How can i avoid this? NULL doesn´t work and key($type_2) works only for the first call. If I changed the selection in the first form I must select a radio box in the 2nd form. If I don't do this, the message comes and I can`t change the selection of the 1st form ... hope I could it little bit explain.

  $default = isset($input) ? $input : NULL;
  $form['step_2']['options']['type'] = array (
    '#title' => t('Types 1'),
    '#type' => 'radios',
    '#options' => $type, //get the array from a Taxonomy
    '#default_value' => $default,
    '#required' => TRUE,
    '#attributes' => array(
      'class' => array('clearfix'),
      'onkeypress' => array(
        'if(event.keyCode==13){this.form.submit();}'
      ),
    ),
    '#ajax' =>  array(
    'callback' => '_type_ajax_callback',
    ),
  );

  $default_2 = isset($input_2) ? $input_2 : key($type_2);
  $form['step_2']['options']['type_2'] = array (
    '#title' => t('Types 2'),
    '#type' => 'radios',
    '#options' => $type_2, //get the array of the Taxonomy which is referenced in the 1st Taxonomy
    '#default_value' => $default_2,
    '#attributes' => array(
      'class' => array('clearfix')
    ),
    '#ajax' => array(
      'event' => 'change',
      'wrapper' => 'calc-wrapper',
      'callback' => '_type_2_ajax_callback',
      'method' => 'replace',
      'keypress' => TRUE,
    ),
  );

  function _type_ajax_callback(&$form, $form_state) {
    return array(
      '#type' => 'ajax',
      '#commands' => array(
        ajax_command_replace("#floor-options", render($form['step_2']['options'])),
      )
    );
  }

Maybe i need to recreate the $type_2 array, but I didn`k know how i could do this. Need I an extra value recall in the ajax callback?

I found a little solution by clearing the default value after output the form.
unset($form['step_2']['options']['type_2']['#default_value']);

But if the user goes back in the multistep form and comes to this point the default value isn`t set. It will not be recrate like the #options in the form array.


Login from one Drupal instance on another Drupal instance I'm working on a project that has some unconventional requirements.

Basically, I have two sites, each one with an individual Drupal installation and instance. The main site (I'll call it "master") has a lot of registered users, and the other one does not (I'll call it "slave").

I need the possibility of logging into the "master" site through the "slave" one. Like, the "slave" site would have a login form, that would connect to the "master" site and authenticate the user.

I've thought of using APIs like OAuth for this, but I didn't find any solid documentation or tutorial of how to do this with Drupal.

Observations: I can't make them multisites, they are two isolated Drupal instances. And it must work for Drupal 6.

Can anyone give me some directions?

Have a look at the Single Sign On module. It's only for Drupal 6, which is what you need, but it's not actively maintained. If it works as advertised, I think you are good to go.

There is also the Bakery Single Sign-On System, but I don't think it fits your specs and requirements.


Change five module user rating text I am using fivestar module to rate the content. I have added it to my view and full node view. I have configured it only to display number user voted the content. By default it is displaying as No votes or (10 Votes) and so on. I want to alter the text as (0) or (10) and so on. How can I alter the text.
 In contrib it  is written in http://www.drupalcontrib.org/api/drupal/contributions!fivestar!includes!fivestar.theme.inc/function/theme_fivestar_static/7

You programmatically alter it via hook_node_view_alter()

  This hook is called after the content has been assembled in a
  structured array and may be used for doing processing which requires
  that the complete node content structure has been built.


Remove all previous cart if have same product creator Thanks a lot joshmiller, but I need this rule on before add product to cart react event, not after save commerce order.

I need when user (buyer) klick second button add to cart (for multi order), system check the product creator id first, if the product creator id for the second order clicked is same with previous (where is actually on cart) system cancel the previous clicked order.

With this scenario I want to limit order only from same product creator for one times order. So if buyer want to continue order from different product creator they have to do after first order completed.

Any suggest how to solve this using rule?

You simply need to create a rule that reacts on order creation, searches for existing orders for that user, and cancels those orders.

Next, add the condition to make sure you won't pull all anonymous orders. If you allow anonymous orders, you might have to implement some sort of custom session searching for orders.

Next, add an action that brings in a list of entities (we're going to pull a list of orders based on owner).

Then, select Commerce Orders

This is what the full action looks like when you've set it up for selecting by order owner's user id:

Next, you want to add a loop based on the orders you've pulled:

Next, you want to add an action inside that loop that changes the status of the orders:

Finally, set the order status to canceled:

Here's an export of the rule:

{ "rules_cancel_previous_orders" : {
    "LABEL" : "Cancel previous orders",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_order", "entity" ],
    "ON" : { "commerce_order_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:uid" ], "op" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "commerce_order",
            "property" : "uid",
            "value" : [ "commerce-order:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "canceled" } }
          ]
        }
      }
    ]
  }
}


Can I update from 7.34 to 7.41 directly? What is the safest way to do so? I have a site built using Drupal 7.34, and now I want the core to be upgraded to 7.41 and would like to know the safest way to do it.

Yes, Drupal Core is self-contained in that any forward version of Drupal contains all the updates of intermediary versions of Drupal you are missing. So, you don't have to install and update Drupal manually through every single version of Drupal that is released.

The recommended way is to simply overwrite your drupal site files as per the distributed documentation with Drupal. Put your site in Maintenance Mode and run the update script.

Alternatively, you can upgrade Drupal via Patches:
https://fuerstnet.de/en/drupal-upgrade-easy-way


How can I get the group id of a node using tokens? I try to use [node:og_group_ref], but that gives me the group node title and I need the GID, I am sure there should be a way to get it but I haven't found it

In Organic Groups 7.2 the Node idea and Group id are the same. So if you are using views you can do the following:

Add field "Content: Nid" and exclude if from display.
Any field arranged below the above can use [nid] as a rewrite giving you the Group ID.

Does this help?


(OG) Example function to detect User's roles? Using Open Atrium 6.x-1.2 (Organic Groups 6.x-2.3 inc it's access control.mod), would someone be as kind to provide an example function that would detect the current user's role? It's my understanding OG overrides the standard Drupal permissions page. My end goal is to allow certain roles access to groups they don't specifically have membership (eg: Executive) for a custom OA/OG access control policy/module.

Would some implementation of Rules be possible here?

My skill level: no PHP but just started studying module dev

To test whether the currently-logged-in User has a specific Role, you can do this:

global $user;
if (in_array('Executive', $user->roles)) {
  drupal_set_message("I have the 'Executive' role.");
}


module controller does not respond! I'm trying to create a controller within my custom module, but the controller still doesn't response when visiting the associated path.

Here are my files:

my_module/my_module.routing.yml:

my_module.agreement:
  path: 'my_module/send_consent'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::check_agreement'
    _title: 'Agreement controller'
  methods:  [GET]

my_module/src/Controller/MyModuleController.php :

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

    public function check_agreement() {
        die('hello from controller');
    }
}

To test I visit myproject.local/my_module/send_consent

Any help?

You forgot requirements (which is required):

my_module.agreement:
  path: 'my_module/send_consent'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::check_agreement'
    _title: 'Agreement controller'
  methods:  [GET]
  requirements:
    _permission: 'access content'

See Structure of roots for full details.


How do I create a download link from data in memory? I need to create a Controller that serves data as a download when accessed. That file is not in the file system but in memory; that's why I need a Controller instead of just serve file.

How do I create a download link from data in memory?

My approach is to use a Symfony Response obejct as explained here: The HttpFoundation Component: Serving files.

Firts setup the routing:

mymodule.download_item:
  path: '/myitems/{item_id}/download'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyController::downloadItem'

So the controller looks like:

class MyController extends ControllerBase {
 public function downloadItem($item_id) {

    $fileContent = functionToObtainExternalContent($item_id);
    $response = new Response($fileContent);

    $disposition = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'foo.txt'
    );

    $response->headers->set('Content-Disposition', $disposition);

    return $response;
  }
}


How can I activate a horizontal tab? Drupal 7 has the field group module which contains a horizontal_tab.js file.

Inside this file i found this written

// If the current URL has a fragment and one of the tabs contains an
// element that matches the URL fragment, activate that tab.
if (window.location.hash && $(window.location.hash, this).length) {
   tab_focus = $(window.location.hash, this).closest('.horizontal-tabs-pane');
}

Can someone explain how this would work and what exact url i should call so that a particular tab is activated.

window.location.hash returns the part of the URL after the #, including the #.
Passing to $() a string like, for example, "#tab1" selects any element that uses "tab1" as ID. (Differently, ".tab" selects any elements that uses "tab" as CSS class.)

$(window.location.hash, this) select all the elements that has window.location.hash as CSS selector, using this as context; this is the element on which an handler is triggered.
$().closest() returns then the first ancestor element that matches the selector passed ad argument.


drupal commerce customization I'm trying to build a site for registering educational classes...(sell them)

I want to use Drupal commerce, and add some properties like time,teacher etc. but I want to add some things:

every class has specific capacity. I want users to first, register, then if someone wanted to register, register something like reserved...meanwhile,if sb cancelled order, the reserved people would be registered, after all, we approve the people, no matter registered or reserved, then they can pay....

another thing is that I want that products expire after a while, for example until the tomorrow registration(buying) is allowed.

Is it possible to do these with commerce or Drupal?

I didn't get the first part. About the expiring date you can use Scheduler.

You can decide when you want to unpublish or publish some content (Product display in your case).


Enable "parent":[] in REST export view I have multi level taxonomy with 2 levels, but when I run REST export on it, "parent":[], always stays blank - no matter how many levels there is.

How can I expose relations within taxonomy via restful?

This is a bug in core, see https://www.drupal.org/node/2543726
In the meantime, you could write a new normalizer service that is only for terms.


TypeError on "drush config-export" I've been receiving the following error message when trying to do a drush config-export command.
However, I am able to successfully do the configuration export from the Drupal admin page (admin/config/development/configuration/full/export).

TypeError: Argument 2 passed to [error] Drupal\Core\Config\FileStorage::write() must be of the type array, boolean given, called in /vendor/drush/drush/commands/core/config.drush.inc on line 519 in Drupal\Core\Config\FileStorage->write() (line 140 of /web/core/lib/Drupal/Core/Config/FileStorage.php)
#0
/vendor/drush/drush/commands/core/config.drush.inc(519): Drupal\Core\Config\FileStorage->write('field.field.nod...', false)
#1
/vendor/drush/drush/commands/core/config.drush.inc(448): _drush_config_export('sync', '../data/sync', false)
#2
/vendor/drush/drush/includes/command.inc(422): drush_config_export()
#3
/vendor/drush/drush/includes/command.inc(231): _drush_invoke_hooks(Array, Array)
#4
/vendor/drush/drush/includes/command.inc(199): drush_command()
#5
/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67): drush_dispatch(Array)
#6
/vendor/drush/drush/includes/preflight.inc(66): Drush\Boot\BaseBoot-bootstrap_and_dispatch()
#7 /Users/Bcorrigan/sites/flowrite8/vendor/drush/drush/drush.php(12):
drush_main()
#8
{main}.

The only reference I can find to something similar is here: https://www.drupal.org/node/2830047

But I did not have that module installed when I started getting the error. It's installed now, but still getting the error and will probably remove it soon.

I started receiving the error yesterday, reverting to previous version of Git have made no difference in receiving the error.

Anyone else run into this? Know how to fix? Thanks for any help you can provide.

Just try

drush config-export --destination="<folder-path>"

Path should be some writable folder


Translating custom database table fields How can I translate the fields for my custom database table which uses the following schema?

member_id: int
name: varchar(60)
i_prefer: varchar(50)

I need to translate the string that is displayed for the 'i_prefer' field. I know how I should represent this in template page (<?php print t($query->i_prefer); ?>), but the translated string will not appear until I provide the translation. I checked in 'Regional and language > Translate interface'; I can not see my text.

How can I do this?

The first argument of t() is a literal string, not a dynamic string. If you use a dynamic string, that will be translated only if it matched a literal string another module passes to t().

For example, if I use the following code, the string will be shown translated (when a translation for the currently enabled language exists), as 'E-mail address' is used as argument of t() from user_account_form().

  $label = 'E-mail address';

  $form['mail'] = array(
    '#type' => 'textfield',
    '#title' => t($label),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#required' => TRUE,
    '#default_value' => '',
  );

If the values contained in that database field are limited to specific values, then you can add the following code to the module you are using.

function mymodule_translated_strings() {
  $strings = array(
    t('first value used for the database field'),
    t('second value used for the database field'),
    t('third value used for the database field'),
  );
}

The function doesn't need to be called; it is required only to have a call to t() for each literal strings that contain one possible value of that database field. Clearly, this is convenient if the database field can assume values which are restricted to a small set of values. If the values assigned to the database field are input from users, then this approach is not possible, since the users can (theoretically) enter any value.

For the other cases, the Internationalization module could be helpful. As described in Translating user-defined strings (module developers), i18nstrings() is the function that should be used in this case.


open a lightbox2 containing a flowplayer video from a menu link Is it possible to make a link from a main menu to open a lightbox2 that will contain a flv video?

I have flowplayer installed but not swf tools

I thought of doing it with javascript but I'm sure there is another way

Add rel="lightvideo" tag, it will popup the video, It also have the option to set the size of the modal window, for more information see the readme.txt

Google video example


Default to original language in nodes list I set up a multilingual blog with Drupal 8 (in English and Chinese), I want to list articles according to current language in the front page.

However, if an article does not has an translation in the current language, I want it to default to the original untranslated version(whatever language), with a hint like "This content is not available in Chinese, we are showing the original article in English."

Assuming that I have 3 blog articles (nodes), with or without translation:

Article 1 (original language: English; translated to: Chinese)
Article 2 (original language: Chinese; translated to: English)
Article 3 (original language: English)

When a user visits the English front page at example.com/en, they will see:

Article 1 (in English, original)
Article 2 (in English, translated)
Article 3 (in English, original)

which is the default behaviour of Drupal 8.

Now, when a user visits the Chinese front page at example.com/zh-hans, I would like them to see:

Article 1 (in Chinese, translated)
Article 2 (in Chinese, original)
Article 3 (in English, with a hint)

However, Drupal 8 out of the box will display:

Article 1 (in Chinese, translated)
Article 2 (in Chinese, original)

I tried editing the front page as it is a view in Drupal 8, but with the filters in view I could not achieve this.

(Filters in view)

Do I need to implement a custom filter for the front page view? Please suggest where should I start, I have no idea how to do this.

Thanks!

See the solution to How do I get Views content items in "my language" but fall back to "default" if the content isn't translated? whether it helps just by configuring in admin. It seems to solve the same problem.

Unfortunately, I have the same problem, and I can't get the solution described there to work. Reading all the issues linked in meta Make multilingual views work, it seems to me that there is no built-in solution. I tried to implement a hook_views_post_execute() and to filter the ViewExecutable $view manually, like in the following, but it did not work - either still shows multiple translations per entity, or entities are missing:

# File modules/contrib/modulename/modulename.module
# Enabled in admin/extend
function modulename_views_post_execute(ViewExecutable $view)
{
  $contentLangcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();

  # trying either one of:
  # $Filtered = filterLangcodeOrEn($contentLangcode, $view->result);
  $Filtered = filterNodeOnce($view->result);

  $view->result = $Filtered;
  $view->total_rows = count($Filtered);
}

function filterNodeOnce($rows)
{
  $Nodes = array();
  foreach ($rows as $row) {
    $Nodes[$row->nid] = $row;
  }

  return array_values($Nodes);
}

function filterLangcodeOrEn($contentLangcode, $rows)
{
  # group by nid
  $EntitiesLangcodesRow = array();
  foreach ($rows as $row) {
    $EntitiesLangcodesRow[$row->nid][$row->node_field_data_langcode] = $row;
  }

  # select
  $Filtered = array();
  foreach ($EntitiesLangcodesRow as $LangcodesRow) {
    if (isset($LangcodesRow[$contentLangcode])) {
      $Filtered[] = $LangcodesRow[$contentLangcode];
    }
    else if (isset($LangcodesRow["en"])) {
      $Filtered[] = $LangcodesRow["en"];
    }
  }
  return $Filtered;
}


Drupal Commerce add multiple products to cart at once with different attribute values I'm developing a shop based on Drupal Commerce which sells customizable objects.
I'd like to be able to order t-shirts of a certain type in different colors an sizes (like 5 orange ones size XS, 10 blue ones size L...).

This would normally be done by going to the product page, selecting "orange" as the color, "XS" as the size, adding it to the cart, then going back to the product page...but this is too complicated.

So I'm wondering what is the cleanest approach to achieve this.

Here is an example of the result I would like to obtain (choose a color, then a size, then a quantity, do it as many times as you need, then only click add to cart) :
http://www.objetrama.fr/tee-shirt-personnalise-femme-melrose-150-gr-m.html

I think this could be done by finding a way to send multiple add to cart requests from the same page using ajax (tried this approach with not much success).
Another solution would be to create a custom add to cart function which accepts multiple products with different attribute values.

Since your not sending a single SKU, you could just overwrite the validate and submit handler for the add to cart form and then, using the existing validate and submit handlers as a blueprint, write your own logic to add multiple products. You'll want to make sure you create line-items for each of the variants your adding to the cart so that pricing is calculated properly, but it should be a fairly straightforward process.


What should a bilingual site look like from the backend? Suddenly I have lost track on my new build D7 German/English site. Nothing I attempt seems to work. I will tell more about the problems below but I think its hard to help me there as long as I am not sure if the base is correct. So, my concrete question is:

How should the mainmenu of a bilingual D7 site look like, i.e. is there only one main menu and the translations of the links can just be seen after clicking on them?

Home
About Us
-Team
-Jobs

Or should there be a menu tree for German and another one for English?

Home
About Us
-Team
-Jobs
Start
Über uns
-Mitarbeiter
-Karriere

(Both is possible and I am still strugelling to understand if this is a bug or a feature. See Why are there so many different ways to translate menus?)

Well, here are some of the problems I thought I overcome and which now seem to be everywhere on my site:

Sometimes, a translated site appears as an item on its own in content list, sometimes the translation seems to be stores in the main language item.
On some pages I may not click on English although there exists a translated version of the site although it should be linked as far as I see.
If a link works, the bread crump path differs from the real path:

German:

Start / Über uns / Karriere

English:

Home / Jobs

I figured out that a correct localized main menu should be bilingual or multilingual and therefore look like this:

Home
About Us
-Team
-Jobs
Start
Über uns
-Mitarbeiter
-Karriere
Infographic (EN: Infographic, DE: Infografik)

The possibility to save localizations inside of the node (my possibiliy 1 in the question) are for pages that are not necessary to translate (e.g. they show only a infographic, as in my example above) but the links pointing to them.

Hope this helps other people with this question.


How to create a organic-group-alias/content-type subpage? I've created a page via views that show a list of all the nodes of a specific content type in a specific group.

/node/groupid/post lists all the nodes of type post in groupid.

But what I really need, is to be able to use the groups path alias. So:

/group-name-here/post should work for /node/groupid/post.

How can I do that?

site specs

Drupal 7.41

Views 3.11

OG 2.7

Pathauto 1.3

Views treats aliases the same as node/id. So, in the view, just set the path to node/id/post or similar.


Private files get Access Denied for any non-admin role but only on server Very odd problem. I have a bundle where a user uploads a file to a private file field. When viewing the bundle; they see the file listed and can see it is linked to the file; but when clicking the file, they get Access Denied. This is on a CentOS 7 server.

The part which makes this odd is that the site is version controlled and the same code is running on my local Windows development machine. I just grabbed a copy of the server db and installed on my local. So, technically, the sites should be identical. On my local, the user is able to view the private file.

Normally this would lead me to think it is a server issue; but, anyone with Administrator role can view the file. This suggests it is something controlled by Drupal.

On the server I have created a virgin bundle with only a single new file field; and the problem persists. So it appears to not be bundle or site config related.

The issue is due to the File Entity module. This was still enabled on our site even though it has been deprecated. Once it is uninstalled; private files work as expected.


Pointing the Views handler for Node Body at another field handler I want to be able to use a CCK field as my node body without affecting interoperability with Views generated by independent modules. Using hook_data_alter(), I have attempt to re-target the Views node body handler to look at the handler CCK has generated for my field, field_body. Unfortunately, I get some errors when I try to make use of my proposed solution.

/**
 * Implementation of hook_views_data_alter().
 */
function fieldbody_views_data_alter(&$data) {
  // When node_revisions table is added, join in content_field_body too.
  $data['node_revisions']['table']['join']['content_field_body'] = array(
    'left_field' => 'vid',
    'field' => 'vid',
  );

  // Use field_body handler info for node body.
  $data['node_revisions']['body'] =
    $data['node_data_field_body']['field_body_value'];

  // Really emphasize that we are using a different table.
  // Since this isn't doing anything, it may be redundant.
  $data['node_revisions']['body']['table'] = 'content_field_body';

  // A couple tweaks so it's a friendly Node Body replacement in the UI.
  $data['node_revisions']['body']['group'] = t('Node');
  $data['node_revisions']['body']['help'] =
    t('Full body text of the node.');
}

This code appears to work, but when I try to use the handler in practice, I get a warning:

user warning: Unknown column 'node_revisions.field_body_value' in 'field list' query: SELECT DISTINCT node.nid AS nid, node_revisions.field_body_value AS node_revisions_field_body_value, node_revisions.field_body_format AS node_revisions_field_body_format, node.type AS node_type, node.vid AS node_vid FROM node node LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid LIMIT 0, 10 in ../workspace/oa/profiles/openatrium/modules/contrib/views/includes/view.inc on line 771.

My interpretation of this is that the code is not pulling in the content_field_body table when the field is used, instead it just tries to use node_revisions.field_body_value.

Looking for any answers that resolve this problem or suggest a better strategy for my goal.

EDIT: Ugly Fallback Option

Use hook_views_default_views_alter() to scan every View for a defined body field, and swap it out for a standard CCK field. However, this will break all kinds of things, and not be very performance on cache clears.

As the database field you are using is external to the node_revisions table, you should probably declare a relationship, in the same way done from Views for the uid field.

// uid field
$data['node_revisions']['uid'] = array(
  'title' => t('User'),
  'help' => t('Relate a node revision to the user who created the revision.'),
  'relationship' => array(
    'handler' => 'views_handler_relationship',
    'base' => 'users',
    'base field' => 'uid',
    'label' => t('user'),
  ),
);


Printer Module: Show link base on Content Type Let say I have content type A, B, C and D. How can I show the Printer Module's Link on B and D only? The one with PDF version, and ePub Version.

Edit the content type and go to Printer, email and PDF version and choose to display or not.


Hide a user in People List I have a super user(user 1) that I want to hide in people list (mysite.com/admin/people).

Is there anyway to filter it out? I couldn't find a hook unless I just missed it. I know I could create my own view and easily filter it but then I loose the bulk operation which I need to keep.

EDIT:  here is the "why". I'm building an intranet system with drupal. User 1 is the super user that I want to keep for myself to be able modify advanced features of the intranet. I have created another "admin" roles that can manage content, users, roles, etc. I have a few dozen modules installed, but the ones applicable per this issue is user protect, workbench, and permissions lock.

There is a bug in user protect that allows my admin to delete the user1 account via the bulk operations on the people page, so I want to just hide it altogether.

Put this in a custom module and it will effectively remove User 1 from the People list, but only there.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  unset($form['accounts']['#options'][1]);
}

But as Free Radical pointed out, if you say why there might be better solutions.

Cheers,


406 error on ajax calls in Drupal 8 Yesterday I upgraded from drupal 8 beta 3 to beta 10. I noticed all my ajax calls are now getting error 406 (Not acceptable).

This is my route:

switch_customer.user:
  path: '/profile/get/{template}'
  defaults:
    _controller: 'Drupal\switch_customer\Controller\CustomerController::renderDisplay'
    _title: 'User Info'
  requirements:
    _permission: 'access content'

Controller:

$content = array(
            '#theme' => $templateName,
            '#items' => $items
        );

        $content = render($content);
        return $content;

Ajax call:

    jQuery.ajax({
        type: "GET",
        url: '/profile/get/info',
        success: function (data) {
           jQuery(".profile-sidebar-info").empty().append(data);
            if(cb){
                cb();
            }
        }
    });

I can't figure out what I'm doing wrong? All my calls were fine in the previous beta. Can someone assist me?

Thanks!

Your controller must return an array or a Response object.

If you want to return the content as-is (no "drupal" around it):

return new Response($content)

If you want to return a normal, full page, then just return the render array.


D8 -> D8 node migration I assumed that, since migrate is now in core, migrating nodes from a Drupal 8 site to another Drupal 8 site would be baked in. However, it seems not so.

I have already exported all the node configuration: fields, storage, etc. How can I get the actual node content from a Drupal 8 site to another Drupal 8 site?

As of Jan 11, 2017, there are still no Drupal 8 sources available, per Berdir, Mike Ryan, and others.

To follow along at home, see this issue: https://www.drupal.org/node/2607524


Is it a problem when entity field storage info is not registered in the key_value table? This is a Drupal 8 (beta 15) site, basic, few content types. On the status report page it says:

Entity/field definitions
    Mismatch detected
    Mismatched entity and/or field definitions.

After investigation it turned out, this is caused by a few fields. The Drupal\Core\Entity\EntityDefinitionUpdateManager::getChangeList() is reporting them, because their original storage definition is missing from the key_value table for the column-collection: entity.storage_schema.sql

(The column-collection = config.entity.key_store.field_config entry is there for all fields.)

My question is - how can we fix this? All configuration is stored in configuration files (staging directory) - including all fields yml files. The configuration manager reports no difference, export will keep the files the same, and import will not change anything. drush updb will report no updates as well.

Is there a command we should call in an update hook to sync/register this storage info? Any idea?

It will depend on what exactly is reported from getChangedList() but what is happening is that a module needs to update the entity schema with something like:

\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition('the_field_name', 'node', 'node', $field_storage_definition);

Everything you need to know is in the change record: https://www.drupal.org/node/2554097

There is also an effort underway to provide additional information on the status page: https://www.drupal.org/node/2554911


Does a sub-theme needs the main theme enable? Just to clarified a doubt.
But when creating a sub-theme, is it necessary to have the main theme enable ?

Thanks

No, it is not necessary. You need to have your base theme installed, but you don't need to enable it: https://www.drupal.org/node/225125#comment-7716513

EDIT: Note that if you want to access the settings for your base theme, you will need to enable it, as noted by @MPD in a comment below.


Where is comment admistration template located? I have a Drupal 7 sub-theme based on Bootstrap 3 theme, the comment admin page (http://www.example.com/comment/46849/edit?destination=admin/content/comment/approval) looks as shown below. It is however missing the ability to edit Author and Url fields. I would like to know which template file I need to edit to get this functionality.

If, for some reason, the whole Author fieldset is hidden, be sure to check the HTML first, then you can also use the devel module for some dpm-ing in yourtheme_form_comment_form_alter.

Something like this should force the fieldset to be rendered:

function yourtheme_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['#access'] = user_access('administer comments');
}


How to make a checkbox field required when a radio button is selected. I need to show a validation error message when a radio button is clicked but none of the checkbox is checked. The checkbox field is optional in content type. Should be required when radio button is clicked. How can it implement this programaticaly. Not interested to add conditional field  module for a single requirement.

In form alter use this code

function my_module_form_alter(&$form, &$form_state, $form_id) {
      $radio = $form['#node']->field_radio['und'][0]['value'];

      if($radio == 1){//if
         $form['field_checkbox']['und']['0']['value']['#required'] = TRUE;
         //OR
         $form['field_checkbox']['und']['0']['#required'] = TRUE;
      }
}


Show fields of content type B while keeping filter criteria as content type = A in view I am creating a website in drupal.

I have two content types first is Article and second is Author

Article contains following fields:
 Title, Body, Author-name, Language

Author has following fields:
 Name, Year, Info

Now In a view I want to show the Article name, its author-name and the year of that author!

How can I do this?
Thanks

You need Entity Reference, In your Article content type, create the author field as an entity reference field and refer it to the Author content type. After that you can create a view and add a relationship of Entity Reference and you will get the related fields. For further read, refer here


Is the views module a viable options for creating reports with calculated totals? I have an application built in Drupal 7 that records properties as nodes and relates property nodes to charge nodes and payment nodes.

I would like to add the ability to view a report by selecting a property and specifying two dates, a start date and an end date for the report, that shows a total of payments, a total of charges and then a balance total for a particular property.

However, the charges content type is only used to record additional charges to a property. There is a monthly service charge which is stored as an amount in a field of the property node. So when generating the report, I simply add one service charge payment for each month the report spans.

A summary of the report:

Select a property and give a date range.
Produce a list of charges by :

Adding one service charge for each month between the two dates.
(Note: The service charge amount is given in a field of the property node)
Adding amount from all charge nodes related to this property.
Give a total field for all the charges.
Show all payments from payment nodes related to this property.
Total the payments.
Give a balance total(charge total - payment total)

What I can't figure out is if views can build the report I need.

Can this be done by adding calculated fields to views, in particular the service charge payments, or do I have to do this in a template file (views-view--foobar--page.tpl.php for example)?

I know how to get all payments and charges related to a property into a view, but I am not sure where to go from there. Maybe this comes down to personal preference, but this is my first venture into views and I would appreciate some advice on where I should be concentrating my efforts!

Another Module you can consider is the views summarize

  Enables an extra display style which displays summaries of a column on
  the last row.

You can also use the views calc mentioned by @Felix together with the views aggregator module


How to exclude contributed modules from being upgraded when we run composer install or composer update? I want to exclude contributed module Ubercart from being upgraded when we run composer install or composer update ? What change should I add in the composer.json so that it ignores ubercart contributed module ?
Seems to be simple question, but I have not been able to figure it out.

In composer.json, you remove the ^ and specify the version
Ex: Normally most modules are like this:
"require": {
    "drupal/commerce: "^2.21",
},

and to lock it, you change to
"require": {
    "drupal/commerce: "2.20", // will always install version 2.20 and never update.
},

But because Ubercart is in Alpha, you'll see its currently
"require": {
    "drupal/ubercart: "^4.0@alpha",
},

And to lock needs to be
"require": {
    "drupal/ubercart": "4.0-alpha3", // will always install alpha 3 and never update.
},


How do I change the date format depending on Start and End date in Drupal 7 I have a content type called 'Events' including the fields:

Title
Thumbnail
Date (Can be a start, or both a start and end date)

I have created a view that takes this content type and outputs it as follows:

Exhibition
Thumbnail
17 December 2015 or 17 December 2015 - 23 December 2015

My question is how can I can change the output of the field if the 'Date' field has a start date and an end date.

I am using the Event Calendar Module to create my events.

Can you offer a solution? Thanks in advance.

Enable the Date Views module

In views, click on your field and change Date Format to Custom

For Custom Date Format: you can put something like this m/d/y  or M d, Y

You can format it however you want by using the format characters from the PHP manual


Core jQuery not working in Bootstrap theme I am using Bootstrap 3 subtheme and Drupal 8. For some reason when I add the dependency core/jquery it does not work. What am I doing wrong?

mysubtheme:
  css:
    theme:
      css/slippry.css: {}
    header: true
    js:
      js/slippry.js: {}
  dependencies:
      - core/jquery

The only way I can get jquery to load is when I put the jquery.min.js URL into my page.html.twig file.

Yaml is heavily indentation oriented.

There are yaml validators like: YAMLlint. It will also the intendation for you. But not the wrongly set header option.

You have two indents (spaces) to much before the dash, plus js: needs to be upped too. Also the header property is set wrong, check the docs - if you want the js in the header, it needs its own library definition:

mysubtheme:
  css:
    theme:
      css/slippry.css: {}
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

  This will work ! (but is in the footer)

This is how the two library definitions will look like:

slippry-css:
  css:
    theme:
      css/slippry.css: {}

and

slippry-js:
  header: true
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

You'll need then to add both libraries!

Maybe this will work too:

mysubtheme:
  header: true
  css:
    theme:
      css/slippry.css: {}
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

To debug your libraries, use libraries_ui


How can I enable the Front Page on minimal profile? I installed D8 using the minimal profile but it does not have or does not enable the front page view, redirecting requests to the user page. How can I enable the standard front page (with the recent posts)?

I got it. So, to document the solution:

Enable Views and Views UI modules
Either set the Front Page to the now-available frontpage for the traditional recent posts page

Another way (which was more suited to my intents) is to create a new content type (e.g. Static Page), create a new node of that type and set the site frontpage to that. This is useful when you are developing a theme with a custom frontpage template featuring several regions to be filled with different views.


How do I find the role id from an og group role name? I need to retrieve the rid to assign the 'student' role part of an og group.

I found this post in regards to user roles How do I find the role id from role name?

$rid = array_search('student', user_roles());
og_role_grant('node', $id, $user->uid, $rid);

Is there also a function for og group roles?

Found a helpful solution using a db query https://www.hashbangcode.com/article/load-drupal-organic-group-role-name

$roleid = db_query("SELECT rid, name FROM og_role WHERE gid = :gid and name = :name ORDER BY rid",array(':gid' => 14, 'name' => 'student'))->fetchAssoc();

Let me know in case there is any other or better solution, thanks!


Autocompleting line-item fields in Drupal commerce First off all I'm rather new with Drupal & Drupal Commerce. I'm going to do my best to describe what I have done and tried.

I'm developing a website where people can register (buy) a place in event. One of the things is that on the "add to cart" page they should be able to give some information like name, club, etc.

I added some fields to the line item "Product" like for example a textfield name Club and where I selected the option "Include this field on Add to Cart forms for line items of this type" so that it is shows in my add to cart form.

The problem I now have, is that I want (for a start) autocomplete that line-item field Club using #ajax and a ajax callback.

I started off with a hook_form_alter. I dumped (after checking the form id) the $form variable (with dpm()) to look for the Club #textfield so that I can modify it to include #ajax or #autcomplete_path, but I can't find that element.

The only thing I see is an array line_item_fields containing field_club, field_name (my fields that I attached to the line item) of the type #container (and I looked for a #texfield node within it, but didn't find it). I tried adding #ajax to it but that didn't work.

To be honest I'm totally stuck now as I don't know how to proceed further with this. Is it even possible to attach #ajax or any other attributes to a line-item field visible in the add to cart form ?

If you change the field from a simple text field into an entity reference field, you can create the different clubs as nodes (seems to make sense, since you could then write info about each club on your site). Entity reference comes with a built in autocomplete.

You could also use taxonmy terms and taxonomy reference field instead if you don't want to create a node for each club. Either way should work just fine, as both have autocomplete built in.


How can I print article author profile picture? I have a blog where basic author information needs to be printed out.

Basically, I want to print author name and profile picture in my article teaser template.

I tried googling but none of the answers seemed to help.

Can I somehow access Author object?

Put this on top of your node.html.twig or similar template

{%
  set author_pic = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.uid.entity.user_picture.entity.uri.value,
    '#attributes': { class: 'authorImg' },
  }
%}

Use this anywhere in the same template you want to output the author image

{{ author_pic }}