Ability for user to flag or select multiple nodes from view listing I am creating a page where I have a view listing about 100 nodes of a specific content type and then underneath that I have a contact form. When visitors (logged out users) come to my site I would like them to be able to select some nodes from this view that they like. Either with a checkbox next to each one of them or by some other flagging system. When they then complete my form the specific nodes they have chosen will be sent with the form submission.

Possible Solutions:

Create a template file for the view and add in a checkbox in front of each node.
Use the flags module and pass the selected nodes when submitting.

I've never done something like this before so any help would be appreciated!

Here is a solution with webform and flags:

1. Create a small module.
You can create a very simple module for it - an info file and a module file with your functions. https://drupal.org/node/1074360

2. Implement hook_webform_submission_presave().
This will intercept the form data on the webform submission form submission form before it gets saved in the database.

3. Get the flags that the current user flagged with flag_get_user_flags().
You will receive an array of flags, that you can process as you like, add to form results array for later use, or, if you have a hidden text area called 'flags' in your form, insert that data there as a formatted text.

So, in totality, it will be something like this:

function leadflag_webform_submission_presave($node, &$submission) {
  $nodes_list = '';
  $title = '';
  // Get the flags.
  $flags = flag_get_user_flags('node');
  // Get the nodes.
  if (!empty($flags)) {
    $flags = $flags['flag_name'];
    foreach ($flags as $flag) {
        $nid = $flag->entity_id;
      // Get node data. Delete to not get node titles.
      $node = node_load($nid);
      $title = $node->title;
      // Combine data.
      $nodes_list .= 'node/' . $nid . ' ' . $title . ",\n";
    }
  }

  // Update some component's value before it is saved.
  $component_id = 4;
  $submission->data[$component_id][0] = $nodes_list;
}

This function gets flagged nodes and populates the webform component 4 with node/nids and titles, like this:

node/10 Node Title of node 10,
node/21 Node Title of node 21, etc

The function gets the flags and puts them in form component 4. You need to hover your mouse over your textarea component edit link on the webform components edit page to see what component number it actually is, in the edit link url. Replace the component number in code with your actual component number.

There is a section (lines 13-15), that loads nodes to get their titles. Doing node loads is somewhat an expensive function. It's Ok unless you expect dozens of submissions per minute though. But to not have node_loads, and to only have a list like 'node/10, node/15' without titles, you can delete these lines.


Exposed filters drop down select translated but not displaying on view The field items are properly translated but they don't show up in the views exposed filters.

Can be seen over here on the French page:

can be seen here:  http://sandbox.vuxi.com/fr/node?qt-qt_index_search_b_a_u=1#qt-qt_index_search_b_a_u

For translating exposed filters, you need to enable all translation modules FIRST. And THEN create your views.

Because there is a multilingual option to pick filters, the translatable one.

User: Example (field_example:language) (translated)
Language - Appears in: user:user.

So if you want a multilingual site, install all translation modules FIRST, and then create your views with multiple filters.


Taxonomy vocabulary templates I have three taxonomy vocabularies in my site and one of them using custom template files.. Parent and child term pages and that's ok.. But I don't want to use these template files for two other vocabularies.

I was trying to use TVI module and I get nice views for these vocabulary terms, but I have one huge problem. It messed up my third category page.. It's override template files.

3 vocabularies: Articles, Blogs and Notes..

Articles uses parent-term.tpl files and it's ok, but blogs and notes uses views with TVI module. When I enable TVI module my article category pages messed up..

So what I can do? I love this module, but I don't want automatic override article term pages or nothing.. Only use this module for blog and notes category pages.

To use TVI with individual vocabularies instead of all vocabularies, first make sure it is not globally overriding your vocabulary term pages. Go to Admin > Configuration > User Interface > TVI Settings (admin/config/user-interface/tvi) and uncheck the Use view override checkbox.

Then edit each vocabulary to apply the TVI view override individually. Admin > Structure > Taxonomy > edit vocabulary. In your case, you would edit your Article vocabulary and make sure the Use view override checkbox is unchecked.

Then edit the two vocabularies you do wish to override with the appropriate view. The fields for selecting the view appear once you check the Use view override box:


views filter show node only one time? I have a view, and i filter the nodes based on a list of tags. If one node has more than one matching tag, it's displayed more than once. Can you filter those out? Want to display them only once...

In your view under "advanced", next to "query settings" click "settings" and check "Distinct". This option makes sure every node only gets displayed once.


Starting a views list from the nth element I have two views blocks. One displays the latest news item. I would like the other block to list 4 next latest news items starting from the second latest (as I have already displayed the first one).

Can I achieve this via the view's admin interface?

Yes you can, Under pager settings, offset first four items. Click on the number of items to get this option

and on the page option settings change the offset.


Remove vertical tabs? I bought a module on Envato. I've already contacted the developer, but he does not respond. The module outputs some vertical tabs.

They are created with this code.

/**
 * Implements of hook_builder_content_info()
 */
function builder_builder_content_info() {
  $blocks = _block_rehash();
  $contents = array();
  if (!empty($blocks)) {
    foreach ($blocks as $key => $block) {
      $contents[$block['delta']] = array(
        'info' => $block['info'],
        'type' => 'block',
        'group' => t('Block'),
        // This is name of group to collect contents in a tab
        'block_module' => $block['module'],
      );
    }
  }

  // node add content
  $contents['node'] = array(
    'info' => t('Adding existing node'),
    'group' => t('Node'),
  );

  //Custom text
  $contents['custom_text'] = array(
    'info' => t('Custom text'),
    'group' => t('Text'),
  );

  // Custom heading
  $contents['custom_heading'] = array(
    'info' => t('Custom heading'),
    'group' => t('Text'),
    'no_title' => TRUE,
  );
  // Insert image
  $contents['image'] = array(
    'info' => t('Insert an image'),
    'group' => t('Image'),
  );

  $contents['youtube'] = array(
    'info' => t('Youtube'),
    'group' => t('Video'),
  );
  $contents['vimeo'] = array(
    'info' => t('Vimeo'),
    'group' => t('Video'),
  );

  $contents['icon'] = array(
    'info' => t('Icon'),
    'group' => t('Icon'),
  );
  return $contents;
}

I can rewrite them in my own function, but I have no idea how to remove them. I thought through $contents['custom_text'] but I'm not sure. Of course, I can remove the original code, but I do not like it.

It looks like unset($contents['custom_text']) is working, but can I run this from another file/function?

EDIT

/**
 * Implements HOOK_builder_content_info_alter()
 */
function builder_gc_builder_content_info_alter(&$contents) {
    unset($contents['node']);
}

The function you are showing is an implementation of hook_builder_content_info(). Without seeing the code that calls that hook, I cannot answer about removing the vertical tabs, but I can just give some hints.

If the module also invokes hook_builder_content_info_alter(), which is normally done from the majority of the Drupal modules using hooks, you can implement hook_builder_content_info_alter() in a module.

/**
 * Implements hook_builder_content_info_alter()
 */
function builder_gc_builder_content_info_alter(&$contents) {
  unset($contents['node']['group']);
}

The alter hook could get other arguments, but the structure to change is always the first.

If the module doesn't invoke any hook_builder_content_info_alter() you need to:

Avoid Drupal invokes builder_builder_content_info()
Implement hook_builder_content_info() using the same code used by builder_builder_content_info() but without those parts that you don't want

This can be done with the following code.

function builder_gc_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'builder_content_info') {
    // Remove the implementation done from that module.
    unset($implementations['builder']);
  }
}

function builder_gc_builder_content_info() {
  $blocks = _block_rehash();
  $contents = array();
  if (!empty($blocks)) {
    foreach ($blocks as $key => $block) {
      $contents[$block['delta']] = array(
        'info' => $block['info'],
        'type' => 'block',
        'group' => t('Block'),
        // This is name of group to collect contents in a tab
        'block_module' => $block['module'],
      );
    }
  }

  // node add content
  $contents['node'] = array(
    'info' => t('Adding existing node'),
  );

  //Custom text
  $contents['custom_text'] = array(
    'info' => t('Custom text'),
    'group' => t('Text'),
  );

  // Custom heading
  $contents['custom_heading'] = array(
    'info' => t('Custom heading'),
    'group' => t('Text'),
    'no_title' => TRUE,
  );
  // Insert image
  $contents['image'] = array(
    'info' => t('Insert an image'),
    'group' => t('Image'),
  );

  $contents['youtube'] = array(
    'info' => t('Youtube'),
    'group' => t('Video'),
  );
  $contents['vimeo'] = array(
    'info' => t('Vimeo'),
    'group' => t('Video'),
  );

  $contents['icon'] = array(
    'info' => t('Icon'),
    'group' => t('Icon'),
  );
  return $contents;
}

The code I am showing should avoid the information is shown in vertical tabs, but it doesn't avoid the vertical tabs are created. The only way to be sure is to alter the function that invokes hook_builder_content_info(). Using hook_builder_content_info_alter(), you are sure to alter the value returned from all the hook_builder_content_info() implementations, while the other snippet I shown just alters the value returned from a module. If there are two modules passing 'node' as group, the vertical tab will be created, since I am not altering what returned from the other module.

Also, the code I am showing removes the 'group' property, which I am guessing sets the vertical tab where the information is shown, similarly to the #group property used by fieldsets.

Alternatively, you can use the following code, which removes completely the information about the part you don't want to see.

// Case 1.

/**
 * Implements hook_builder_content_info_alter()
 */
function builder_gc_builder_content_info_alter(&$contents) {
  unset($contents['node']);
}

// Case 2.

function builder_gc_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'builder_content_info') {
    // Remove the implementation done from that module.
    unset($implementations['builder']);
  }
}

function builder_gc_builder_content_info() {
  $blocks = _block_rehash();
  $contents = array();
  if (!empty($blocks)) {
    foreach ($blocks as $key => $block) {
      $contents[$block['delta']] = array(
        'info' => $block['info'],
        'type' => 'block',
        'group' => t('Block'),
        // This is name of group to collect contents in a tab
        'block_module' => $block['module'],
      );
    }
  }

  //Custom text
  $contents['custom_text'] = array(
    'info' => t('Custom text'),
    'group' => t('Text'),
  );

  // Custom heading
  $contents['custom_heading'] = array(
    'info' => t('Custom heading'),
    'group' => t('Text'),
    'no_title' => TRUE,
  );
  // Insert image
  $contents['image'] = array(
    'info' => t('Insert an image'),
    'group' => t('Image'),
  );

  $contents['youtube'] = array(
    'info' => t('Youtube'),
    'group' => t('Video'),
  );
  $contents['vimeo'] = array(
    'info' => t('Vimeo'),
    'group' => t('Video'),
  );

  $contents['icon'] = array(
    'info' => t('Icon'),
    'group' => t('Icon'),
  );
  return $contents;
}

If this code doesn't work, you could follow the following steps, in order to change the module behavior:

Check which function is invoking hook_builder_content_info()
Verify if there is a reference to that function in one of the hooks Drupal uses (e.g. hook_menu()); the reference could be either direct or indirect (i.e., the reference is for a function that calls the function invoking hook_builder_content_info())
If this is the case, using the alter hook Drupal uses (e.g. hook_menu_alter()), you can change that reference with a reference to a function you write, which uses the code the original function uses, without the part you don't want.

In this way, you aren't directly altering the values returned from hook_builder_content_info(), and you need to copy more of the code used from the module for which you are altering the behavior; this is also means that, for every minimal change in the module you bought, you need to check your code to be sure it doesn't alter the expected behaviour.


Error throwing for user field populated through Views: Filter by an entity reference view I am working on a ticket system in my current project (Drupal 8) where user can assign a ticket to particular user. The user field is populated through entity reference and it is filtered using 'Views: Filter by an entity reference' (users belonged to a particular role need to be shown there). For normal users its resulting in 500 Internal server error. It works perfectly if I give 'Administer users' permission to current user role. But without that it will break. I have given 'view user information' permission to all users. Is there any work around without giving 'Administer users' permission to all users as it is not a viable option.

If you need to show the users from a particular role you don't need to rely on views filter option. Default method is enough, there will be an option to filter the users using roles. I know its the answer that you are seeking. But its a work around. But if you need to add other filter parameters this method will not be enough.


Where is a resource for theming drupal 7 views? I needed to theme a view in drupal 7 for example the slider in this site:
http://fourkitchens.com/

What file must i create to costumize a view slider and the relative button?
In drupal 6 there were theme information and i could create a new "view-example.tpl.php" and costumize it very well but in drupal 7 ?
Thank you you are great,Drupal Answers!!

Views for Drupal 7 also provide theme information. See the advance section or follow the URL (in my case)
example.com/admin/structure/views/nojs/display/[my_view]/[type]/analyze-theme


Limit entity reference widget to unique references I have a entity-reference field that enables multiple-references (cardinality is set to -1). The problem is that it allows multiple 'same' references => it is possible to save two references to one specific node.

I know I can limit that using my own validation function but I have this feeling that there has to be easier way (e.g. some settings that I don't know about).

If there's none then sorry for useless question.

I don't think the Entity Reference module ships with this feature. But the entityreference unique module should be sufficient for your need. It is in alpha mode, so I would check the issue queue to see if there are any security/critical issues with it before using it on a production env.


How to modify sort order using PHP? I want to re-order the results of a View using some arbitrary PHP ( the sort is not possible in SQL ).  I believe I could use either _views_pre_render(&$view) or hook_views_post_execute(&$view) to alter the order of the results. However the $view->result array only contains the number of results that the pager is set to, not the whole result set.

Is there some other method I can hook into the result generation process and alter the order of results using PHP ?

Views will always only return the results for the current page of results.

That is a benefit of paging, since you aren't retrieving all the data if users may only want to see some results.

If you want to sort after the results come from the database then you have to turn paging off and return all results. Then you can sort all the results and display them as you like.

[EDIT]

You mention in your comment potentially using hook_views_query_alter() to alter the paging out of the query but (without having actually tried) I don't think that would work without removing the paging all together, because PagerDefault::execute() does its thing to the SQL after you are altering.

If you want to pursue that idea though, what might potentially work though is you doing Query alteration (tagging) by adding an alter tag in hook_views_query_alter() and then implementing hook_query_TAG_alter(), which would run on the preExecute(), which should be after the pager has acted.

For example:

/**
 * Implements hook_views_query_alter().
 */
function MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    // Add a query alteration tag so that we can alter the completed query before execution.
    $query->addTag('CUSTOM_TAG_NAME');
  }
}

/**
 * Implements hook_query_TAG_alter().
 *
 * Alter queries with the CUSTOM_TAG_NAME tag.
 */
function MODULE_NAME_query_CUSTOM_TAG_NAME_alter(QueryAlterableInterface $query) {
  // Alter the $query object here.
}


How can I display a login and registration form, with an extra field on registration, and hybridauth in a modal? I need to display a modal login and registration form if a user accesses a particular page.

On the registration form, I need to collect a phone number.

I need to show the hybridauth login on the form as well.  Is there a solution, or compatible modules to make this solution?

It's a common login/registration solution, so I'd think Drupal has this already.

Yes, this has a common solution with preexisting modules. Here's the summary with your 3 requirements:

Forcing capture of telephone on registration:

After enabling the Telephone module, you can add a phone field on a user entity (http://example.com/admin/config/people/accounts/fields). When you create the field, make sure the Display on user registration form & Required field checkboxes are ticked to enforce user submission of this data on registration & edit.

Hybridauth Social Login:

After enabling the module, and installing the libraries to the sites/all/libraries directory, configure each social network and set your other login options accordingly.

Modal Popup:

The Modal Forms module enables popup modals for the both the user/login & user/register paths. The popup presents the same login form as you see in Drupal so it will contain the HybridAuth login elements as well. The module lets you configure modal popups on a per-page basis so you can choose the pages where you want login/registration presented as modal form.


I need to add on condition to profile form submit handler profile2_form_submit_handler I need to add on condition to profile form submit handler. I have wrote the condition to profile2_form_submit_handler function which is found under sites/all/modules/profile2/profile2.module location.
I have applied the condition in core file but now wanted to move this set of core to template.php file but it is not reflating.
Anyone please suggest me to make it from hook or something other.
My code is:

function THEMENAME_form_submit_handler(&$form, &$form_state) {
  profile2_form_submit_build_profile($form, $form_state);
  // This is needed as some submit callbacks like user_register_submit() rely on
  // clean form values.
  profile2_form_submit_cleanup($form, $form_state);

  foreach ($form_state['profiles'] as $type => $profile) {
    // During registration set the uid field of the newly created user.
    if (empty($profile->uid) && isset($form_state['user']->uid)) {
      $profile->uid = $form_state['user']->uid;
    }

    // check default image status
    // if there is not any then make first image as default
    $default = false;
    $images = $profile->field_user_image['und'];

    foreach($images as $image) {
        if(($image['field_profile_default']['und'][0]['value'] == 1)
         &&($image['entity']->field_profile_default['und'][0]['value'] == 1)) {
            $default = true;
            break;
        }
    }

    profile2_save($profile);
  }
}

A theme can not simply override a form handler. What you need is a form alter function (hook_form_FROM_ID_alter()) to alter the profile2 form, remove its original submit handler and replace it with your own.

THEMENAME_form_profile2_form_alter(&$form, &$form_state) {
  array_splice($form['#submit'], array_search('profile2_form_submit_handler', $form['#submit']), 1, 'THEMENAME_form_submit_handler');
}

Because your are changing the behavior of your site, this should be implemented in a custom module rather than in the theme. Themes are about presentation.

Also, instead of altering profiles on form submit, you could also implement hook_profile2_presave() to alter the profiles before they are saved to the database, regardless on how they are created (ie. your code will also work for profile created programmatically).


Content type that calls in 5 nodes I have 3 content types

First is contest
Second is contest_applicants
Third is contest_results

People will submit contest_applicants for a contest (with references modules i assume)

When making the contest_results content, I need to be able to select specific contest_applicantsto display in the results. Kinda like nesting the nodes.

I been looking for a module that does something like this hut, had no success.

I would uses views but, it needs to be a content type since it will be multiple contest_results

Is there any module I can use to achieve the above setup? Any help is appreciated.

Sounds like a job for field_collection and entityreference

  Provides a field-collection field, to which any number of fields can
  be attached.


Adding more fields to the registration process In Drupal 7, is there a way to add more fields to the registration process? I was thinking along the lines of birthday, fullname, gender, twitter, etc. Also how do I access this data once it's in, so I can output it to my template files?

Since D7, field management is included in the core. Almost every kind of content has now the ability to be managed with fields.

You can go to admin/config/people/accounts/fields to manage user fields. There is also a tab for managing the display.


How to programatically submit an entityform? My use case:

Anonymous user submits information via an entityform.
The form data ($_POST) is cached and a modal dialog box displays with a login form.
The user authenticates, and the cached form data is retrieved and then submitted.

I've been able to do this with webforms, but I haven't been able to accomplish the same task for entityforms. I can get the form using the following code...

<?php
$entityform = entityform_empty_load('my_eform_type');
$form = entityform_form_wrapper($entityform);
?>

What I've had trouble with is creating a $form_state array with the correct structure and values from the cached $_POST that I can then pass to drupal_form_submit(). My entityform has image, date, and checkbox fields, so that adds to the complexity.

I've been able to manually create and save an entityform submission using the following code...

<?php
$values = array(
  'type' => 'my_eform_type',
  'uid' => $user->uid,
  'created' => time(),
  'changed' => time(),
  'language' => LANGUAGE_NONE,
);

// For brevity's sake, I don't show adding all the fields
// from the cached $_POST to the $values array.

$entityform = entityform_create($values);
$entityform->save();
?>

...but that doesn't provide the form validation and reload on error functionality. Errors such as the wrong size image being uploaded, which is caught during form submission.

When my entityform is submitted, there is also an entityform notification email sent and the user is redirected to the confirm page. I don't want those things to happen prior to the user authenticating.

There's some code in the d.o. handbook, but it doesn't talk about drupal_form_submit().

I'm using Entityform 1.1.

I don't think you can submit entityform using drupal_form_submit() as it's entity, not a standard form.

The best way is to save the entity as you did, but you are missing field_attach_submit which is necessary to perform operations on field data submitted by a form.

The syntax is:

field_attach_submit($entity_type, $entity, $form, &$form_state, $options = array())

Example based on given $form_state:

$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

// Copy top-level form values that are not for fields to entity properties,
// without changing existing entity properties that are not being edited by
// this form. Copying field values must be done using field_attach_submit().
$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);

Alternatively you can submit entity form by using entityform_save(), e.g.:

$form = new Entityform(array('type' = 'my_entitty_form', 'language' => LANGUAGE_NONE));
$form->field_entityform_1 = array(LANGUAGE_NONE => array(array('value' => 'field_1')));
$form->field_entityform_2 = array(LANGUAGE_NONE => array(array('value' => 'field_2' )));
$form->uid = 1; // this is the form id
entityform_save($form);

Source: sushantpaste's gist


Filter view by users without a matching record in the related userpoints table I found out that I'm getting a much better query performance if I use an INNER JOIN of users and userpoints compared to a LEFT JOIN.

Currently, new users have 0 userpoints when they register, I'll change that to 1 point with a rule.

To add 1 point to all users with 0 points I was thinking of using a view and Views Bulk Operations.

To get to "the point":
I can't filter the view to show users with 0 points because they don't have a record in the userpoints table. This is the SQL that views tries to generate:

SELECT ..
FROM
{users} users
LEFT JOIN {userpoints_total} userpoints_total ON users.uid = userpoints_total.uid
WHERE  (userpoints_total.points = '0')

I don't think it's possible to generate a query with views to find users without a record in a related table? Or is there a trick?

I figured it out:

function MYMODULE_views_query_alter(&$view, $query) {
 if($view->name = "nameofview") {
     $query->where[1]['conditions'][] = array('field' => 'userpoints_total.points', 'operator' => 'IS NULL',);
    }
}


Views relationship to second database Is there any possibility to add a relationship in views from a second database to the default one. I.e. I am using a second database which contains one table with a userid. In my hook_views_data I would like to add a relationship from this field to users_field_data uid. How can I do this?

I was logged out. Yes I tried to add field relationship on views settings, but my joined table was not shown. Consider that I want to join from a view showing my table to the users_field_data table, not vice versa.

my view is simply showing the the fields from my custom table. This works. But I can't add a relationship to the second db.
The SQL query is

SELECT my_tracking.id AS id, my_tracking.uid AS my_tracking_uid, my_tracking.event_id AS my_tracking_event_id
FROM {my_tracking} my_tracking
ORDER BY id ASC
LIMIT 25 OFFSET 0

my hook_views_data looks like

$data['my_tracking']['table']['name'] = 'event_tracking' . '.my_tracking';

$data['my_tracking']['table']['group'] = t('Event Tracker');

$data['my_tracking']['table']['base'] = array(
  'field' => 'id',
  'title' => t('Event Tracker'),
  'help'  => t('Contains data about tracking events.'),
  'database' => 'event_tracking',
);

$data['my_tracking']['table']['join'] = array(
  'users_field_data' => array(
    'table' => 'default' . '.users_field_data',
    'left_field' => 'uid',
    'field'      => 'uid',
  ),
);

$data['my_tracking']['table']['provider'] = 'my_tracking';

$data['my_tracking']['id'] = array(
  'title' => t('Record ID'),
  'field' => array(
    'id' => 'numeric',
  ),
  'sort' => array(
    'id' => 'standard',
  ),
  'filter' => array(
    'title' => t('Record ID'),
    'id' => 'numeric',
  ),
  'argument' => array(
    'id' => 'numberic',
  ),
);

$data['my_tracking']['uid'] = array(
  'title' => t('UID'),
  'help'  => t("The user's UID."),
  'field' => array(
    'id' => 'numeric',
  ),
  'sort' => array(
    'id' => 'standard',
  ),
  'filter' => array(
    'title' => t('UID'),
    'id' => 'numeric',
  ),
  /*  'relationship' => array(
    'title'              => t('User who is tracked'),
    'help'               => t('The user associated with the record.'),
    'id'                 => 'standard',
    'base'               => 'users_field_data',
    'base field'         => 'uid',
    'field'              => 'uid',
    'label'              => t('The who is tracked'),
  ),*/
  'argument' => array(
    'id' => 'numeric',
  ),
);

$data['my_tracking']['event_id'] = array(
  'title' => t('Event ID'),
  'field' => array(
    'id' => 'numeric',
  ),
  'sort' => array(
    'id' => 'standard',
  ),
  'filter' => array(
    'title' => t('Event ID'),
    'id' => 'numeric',
  ),
  'argument' => array(
    'id' => 'numberic',
  ),
);

No relationship can be added in views. Previously when I used a single database I was able to add the relationship by using the relatationship handler that is commented out above now. I don't know how to adapt it to 2 databases.


How can I better protect access to all site reports except 'Recent log messages' based on role? How can I better protect access to all site reports within /admin/reports/ (except for Recent log messages)? I know I can hide it through CSS or disable the menu in management menu, but is there a better way to disable it?

I have these role defined (apart from Anonymous and Authenticated):

System Developer (can view all reports).
Admin (can only view 'Recent log messages').

Is there any Drupal function or hook that I can use to reach my goal?

Remove the permission for "Admin" to "access site reports" at

Admin > People > Permissions.

Add hook_menu_alter to a custom module, this part changes the access permission for the admin/reports/dblog menu path

/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Allow access for administrator role to recent log entries
  // Use suitable permission here, e.g editorial "administer nodes"
  $items['admin/reports/dblog']['access arguments'] => array('administer nodes'),
}

Clear menu cache, done.


Using migrate, how can you set the default format to Full HTML? Using the migrate module to import content from a database. One of the fields contains full HTML but on import the text field defaults to plain text. The admin default is set to Full HTML, but even though the imports are being created by admin, it defaults to plain text.

How do you set the default to full HTML for imports? There's obviously a way around this in code but wondering if there's a patch or anyone has advice on the right approach.

In Drupal 6, when you import with the Migrate and Table Wizard modules there is a text field when mapping each field that is empty. Just type in full_html and each node when imported with have full_html entered into that row in the database.


Disable Rich Text in comment field I have installed CkEditor for drupal. But it is showing it for comment form also.
I don't want it to be shown. I dont want the user to have an option to select either.
I just want them to have plain text. How can I do that?

Go to URL as in fig (for page comments on page content type). Change the type of text to Plain text as shown.
You can change the comment settings for article or book in similar way by just replacing page from the URL with the respective content types.


Remove Locale settings from Logintoboggan I have Logintoboggan installed to handle login/registration.

Upon registering a new user it displays an option to set up Locale Settings - I would like to have this removed but cannot figure out how.

I have disabled the site-wide option for users to be able to change locale settings but it still appears at registration/authorisation.

I seem to have fixed the issue by myself (again). For some reason the site-wide locale settings didn't stick so I just disabled and re-enable Logintoboggan and it works fine now


Change CSS rule for small screen with jQuery I am making bacon menu for small screens. I need to initialize menu without showing menu links, so I hide them with jQuery. The problem is that on big screen menu links are still hidden and I don't want that to happen.

I use this code to avoid menu link removal on big screens, but it's not working:

scripts.js
    (function (Drupal, $, window) {

  // To understand behaviors, see https://www.drupal.org/node/2269515
  Drupal.behaviors.offer42 = {
    attach: function (context, settings) {

      // Execute code once the DOM is ready. $(document).ready() not required within Drupal.behaviors.
      // Burger menu for small screen
      $(window).resize(function(){
        if ($(window).width() > 720 ){
          $('ul.menu').css('display', 'none');
        }
      });

      $('#menuButton').click(function(){
        $(this).toggleClass('is-active');
        if ($(this).hasClass('is-active')) {
          $('ul.menu').css('display', 'block');
        }
        else {
          $('ul.menu').css('display', 'none');
        }
        });

} (Drupal, jQuery, this));

SASS:

.menu
  li
   display: block;
   text-align: center;
   background-color: #fff;
   @include media($medium-screen-up)
     list-style-type: none
     display: inline-block
     float: right;
     margin: 0 10px 0 10px
     @include position(relative, -50px null null null)
     background-color: initial;

Resolved.

if ($(this).hasClass('is-active')) {

doesn't allow to show menu links when no class is attached:

else {
          $('ul.menu').css('display', 'none');
        }

So, I modified checking for small screen:

 $(window).resize(function(){
        if ($(window).width() > 720 ){
          $('ul.menu').css('display', 'none');
        } else {
          $(this).toggleClass('is-active');
        }
      });


How do I turn off teasers? I have a Drupal 7 site and on some pages, such as the front page. I don't want a list of teasers to show; I just want a Basic Page to show.  How do I do this?

I have looked in content types, blocks, and in the edit screens of the content items themselves, to no avail!

You have different ways/options to solve your issue.

Option 1:
Create a page node and then set node URL as default front page in admin/config/system/site-information

Option 2:
Create a view page using Views module and set the page url as default front page (same as previous option).

Option 3:
Download and Enable Empty Front Page module and then locate any block you want in the content region.


How can I look up the number of items in a Drupal View? I have several views on my Drupal site. I also have a page that links to those views. I would like to see the number of items (e.g. the number of pages) that are listed in each view:

link to foobar view [5 items]
link to other view [0 items]

Is there an easy way to do this. I suppose I will need embedded PHP for this, but I would like to avoid huge SQL statements embedded in my linking page.

You can get the amount of results in a view using their API calls.

<?php
$views = view::load("viewname");
$view->set_display('default'); //optional, could be default, OR the name of a specific display
$views->execute();
echo count($views->result);
?>

I tested this on views 3 (the current version). For further reading, check out http://groups.drupal.org/node/10129. It's written for views 2, but still relevant.


Views in English and Spanish My site is in English and Spanish.
My question pertains to the Similar by terms module and a custom view that on click shows random filtered by term nodes. How would I create an argument to show Spanish content when in Spanish mode, and English content when in English mode? I realize that I could simply filter nodes for Spanish.
How does the Similar by Terms module recognize the fact the page is in either English or Spanish, and display the appropriate language on click?

I think you should not think about language and let Drupal handle it.

If you install locale module and configure it correctly you will gain what you need:

Install the Locale, Internationalization and Taxonomy translation modules. (The latter is optional.)
When adding a taxonomy term, select "Multilingual options->Per language terms."
When adding a content type, select "Workflow settings->Enabled."
when adding content, select language.


Saving email addresses I create a simple ecard page where users can send some (stupid) ecard to other people.

Now for some reason our clients wants to save all these email addresses, and I'm wondering what the best way to do this is?
Obviously I would also need to show a list in the admin.

I was thinking of just using some newsletter module, but for none I checked there is a function where I can add email addresses using coding.

Does anybody know a quick and simple solution? I have custom coded this page, so I'm looking for a module that allows me to add email addresses in php.

You might as well do it right and use webform. It will literally take you minutes once you figure it out.

And then for the ecard submission, you could install the rules module and pass the form values as tokens (including the email address) telling rules that when a webform with the id of "supid_ecard" is submitted, fire this rule -- http://drupalcontrib.org/api/drupal/contributions!rules!rules.module/function/rules_invoke_event/7

All you'd need to do is setup a custom module with hook_rules_event_info() to tell Drupal about your rules, hook_token_list() to list out your tokens, and hook_token_values() so it knows how to render your tokens. Or use the tokens already available.


Adding status message to mail currently I'm using two hooks in my hook.module. hook_form_alter() and hook_mail_alter().

In hook_form_alter() I use drupal_get_messages() to retrieve the status message.

And I want to use hook_mail_alter() to add this message to the email. But I can't pass the message content from one hook to the other.

A global variable is not working. Is there a better way? Another hook I'm not aware of?

I suppose you have tried to use drupal_get_messages() within hook_mail_alter() as well?

The reason it probably did not return a value is because the default behavior or drupal_get_messages() is to clear the message queue (so it empty the second time). You can however make it persistent by passing FALSE as a second parameter (see the documentation).

So in your hook_form_alter() use drupal_get_messages(NULL, FALSE) and then you should be able to use it again in hook_mail_alter().


Transfer a site from SQLite to MySQL Is it possible to transfer the content of a site that I develop locally with SQLite as a database to the live site which uses MySQL or PostgreSQL when it is finished?

I don't want to have to install MySQL or PostgresSQL locally on my laptop. Can backup_migrate module do it or does it export raw MySQL instructions?

You are looking for the DBTNG Migrator module.

  This module is a UI and Drush interface to replicate a database from one database to another independant of what kind of database server they are. So long as ther are support by Drupal, you can migrate to them, including non-SQL stuff!


Contribute D8 version of an existing D7 contrib project? Can someone describe on how to contribute the D8 version of an existing D7 contrib project? I maintain the D7 project, and further want to add the D8 version of it.

I am struggling with creating 8.x.1.x Dev branch.

Please share any references or steps to follow.

My Project link: Check DNS.

So when I create 8.x.1.x branch, I can see Drupal 7 specific files within that, so I am confused that how should I manage set of files for D8 and D7.

You can use Browse code repository to see your source code on your project page. Currently when you go to list of branches, the 8.x-1.x doesn't exist yet.

To maintain both D7 and D8, you need to have one branch for each, 7.x-1.x for Drupal 7, and 8.x-1.x for Drupal 8.

To create Drupal 8 out of Drupal 7 version, you should first clone your repository as per these Git instructions:

git clone --branch 7.x-1.x your_user@git.drupal.org:project/check_dns.git

then create a new branch:

git checkout -b 8.x-1.x

which allows you to freely modify your files for Drupal 8 version.

Once you did your conversion, you can push your branch back to Drupal.org, e.g.

git push origin 8.x-1.x

To switch between branches, use git checkout command, so you can contribute to both version.

Ideally, you should read more about managing source code using Git. Checkout this GitHub Cheat Sheet.


Distributed authentication system (different domains, separatate databases) We got multiple small websites (microsites) and one main high traffic one with big users base. Right now the requirement is to build authentication system which should allow users to loign with the same identity across the network.

All website are running on different domains, powered by Drupal 6 CMS and have separate databases (so sharing tables with prefix is not an option + it creates a huge mess in the db).

Here is the set of core requirements I came up with:

Users should be able to login with the same credentials to all sites within the network
User’s data sharing between Main site (storage) and all micro sites within the network
Data synchronization across the network when user changes the data (update email or password for example)
The login/registration process should be seamless and consistent
Register on any of the sites across the network and use that identity to login later on.

In the future there might be a need to add openid authentication options.

Basically we are looking at something similar stackexchange does, but not sure if they have central users base on not.

I was thinking about custom solution which will include 2 parts (modules), one will be stored on the Main site for users data storing and responding to requests from clients. Second part (module) will be placed on each microsite, which is going to send requests to the Master. Some kind of client - server setup.

One of the complications I see right away is #3. Data Synhcronization across the network.

I just don't want to reinvent the wheel and maybe some work is already done in this direction.

Looking forward to your ideas on how to approach this project.

EDIT:

Recently I've found couple related threads on the topic:

http://groups.drupal.org/node/24916
http://drupal.org/node/744400

This might be overkill, but have you considered using something like LDAP?

There is an LDAP integration module and an LDAP provisioning module. Both of which work quite well.


Redirect After User Registration if Referred from Specific URL I have been trying to redirect users after filling out the user registration if referred from a specific page on the site with form_alter like so

function custom_markup_form_alter(&$form, &$form_state, $form_id) {

if($form_id == 'user_register_form' && strpos($_SERVER['HTTP_REFERER'],
'/resources/price-sheets') > 0 ) {

    $form_state['redirect'] = 'node/50';

    }
}

If I dpm($form_state) on the user/registration page it shows the $form_state['redirect'] = 'node/50'; as it should. But when I submit the form it redirects me to the home page. I also tried replacing $form_state['redirect'] = 'node/50'; with $_GET['destination'] = 'node/50'; with the same results. I've found a few similar questions, but none of those answers are working for me either, does anyone have a good working solution?

I think you need to set the redirect in a submit handler. Add your custom submit handler to $form and then in your custom submit handler set $form_state['redirect'] to where you want it to go. Doing it in a form_alter could be why it's not working. See Redirecting a Form

function my_redirect_form_my_content_type_node_form_alter(&$form, &$form_state){
  $form['#submit'][] = 'my_redirect_node_form_submit';
}

function my_redirect_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/10'; // the address of your thank you page
  // if you are really, really determined to force the redirect, even if a destination has been set in the url, add this:  unset($_GET['destination']);
  // you could also add a message (this is in addition to whatever message is produced by the nodeapi function): drupal_set_message(t('Congratulations!'));
}


How to make conditional path aliases? In Drupal 8 you can create path aliases by going to: admin/config/search/path/patterns/add

Which allows me to, for example, say that all content of type "blog_post" can have something like this:

/blog/[category]/[title]

The problem is, I want the TOP path to be different, depending on the category. Specifically, I want any blog post that has the category = Competition, to have:

/competitions/[title]

While still being able to have

/blog/[category]/[title]

I can't seem to get this going. Is there a way to do this? I tried creating another aliases but I don't think there is any path I can specify that will give me this?

Solution 1: Without code

Configure a taxonomy vocabulary named Blog category to manage blog categories.
Configure Blog category aliases to /blog/[term:name].
For the Competitions term, override the URL alias to /competitions.
Configure a taxonomy term reference field (preferably single value) on the Article content type. Say, the field name is field_category.
Configure the Article path pattern as /[field_category:entity:url:path]/[node:title].

This is somewhat like what gapple has mentioned above.

Solution 2: With code

Configure a taxonomy vocabulary named Blog category to manage blog categories.
Configure a taxonomy term reference field (preferably single value) on the Article content type. Say, the field name is field_category.
Configure the Article path pattern as /blog/[field_category:entity:name]/[node:title]
Use hook_pathauto_pattern_alter() or hook_pathauto_alias_alter() to change the path pattern depending on the $context.

This is what I did for my problem. This way, you can choose whatever alias you want for your taxonomy term.


"#markup" form element can't have children I have my form, but any child of the "#markup" element will not appear when the form is being rendered.

$form['html'] = array(
  '#type' => 'markup',
  '#markup' => '
My Heading
',
  '#tree' => true,
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);

In this example the "element" form field will not be rendered.

Is this a Drupal bug, or do I need to do something specific?

Not being able to use "#tree" with a "#markup" element seems a bug of Drupal, as the reference page for the form API reports that "#tree" is supported by the "#markup" element.

As workaround, you can also use the "#prefix" property, as in the following code:

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
  '#prefix' => '
My Heading
',
);

If it is not rendered as you expect, then you can simply remove "#tree" from your code, which doesn't seem to be needed, if all you want is to render the
My Heading
 tag before the form fields. The form API renders the elements following the order they appear in the array; if you want to alter the order, you can use the "#weight" property.

$form['html'] = array(
 '#type' => 'markup',
 '#markup' => '
My Heading
',
);

$form['html']['element'] = array(
  '#type' => 'textfield',
  '#title' => 'Foo',
);


How to use the Rules module to lock English nodes from editing? I need to lock all English nodes from editing because translators sometimes change English nodes by mistake instead of creating translations for them.

Can it be done with Rules?

I guess it might work with the Rules Condition that uses a data comparison node:language equals English.

What Rules Action can be used here?

For the event, "a node is updated", use the action "set data value".. Unchanged node's body > Changed node's body and set a site message explaining that the translation wasn't saved.

I'd also make the rule only apply to the translator role.


Discount for each additional Item I'm trying to set up a discount in Drupal Commerce for each additional product ordered. The first product is full price and all subsequent products should be discounted $20. I can have every product discounted, but have not been able to have the first product at full price. For example, if I have 3 of the products in the cart the discount is $60 (all three products discounted) and not $40 (only the second and third product should be discounted).

You could potentially add a "data comparison" condition to your existing discount rule that would effectively do this:

current-user:order:line-items:0:commerce_product:id != product:id

Which would say "only continue if the first line item's product id isn't the same as this product id" but would totally fail if you had some other line item added to your cart before your first product. If that is the case, then you would need to create a custom rules condition.


How to filter Date Views with correctly timezone I am using latest Drupal 8.2.5 for Live-score website. I have the Views for display all games daily. It's including DateTime for schedule and storing on Europe/London timezone (by default).

On the views FILTER CRITERIA, I added Match_Date_Fields between:

Today
+1 day

For getting the matchs from today events and next events.
So, the views will filter by default timezone (london), sure. But when the visitor access to my site from Thailand. This filter seem to wrong. Because here difference between timezone from London to Thailand.

For example: The game is play on "January 15, 2017 19:45" for London timezone, but from Thailand it's "January 16, 2017 02:45".

I made it successfully print with depends on the local's time zone. But have no idea How to filter with correctly local's timezone?

Ok, I made it working.
My solution is created a custom drupal 8 module with the file: .views_execution.inc inside your module folder.

Inside that, I added function modulename_views_query_alter($view, $query) with:

//Filter by timezone for bettingsafe's local ip
switch ($view->element['#name']){
    case 'league_match':
        $key = 0;
        foreach ($query->where as $key => $value){
            $key_2 = 0;
            foreach ($value['conditions'] as $key2 => $condition){
                $length = strlen('DATE_FORMAT');
                if (substr($condition['field'], 0, $length) === 'DATE_FORMAT'){
                    $condition['field'] = str_replace('DATE_FORMAT(<date field>', 'DATE_FORMAT(CONVERT_TZ(<date field>, <from timezone>, <to timezone>')', $condition['field']);
                    $query->where[$key]['conditions'][$key_2]['field'] = $condition['field'];
                }
                $key_2+=1;
            }
            $key+=1;
        }
    break;
}

From my server Centos, I install the tool CONVERT_TZ:

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql -p<sql root's password>

Restart mysqld and clear Drupal cache.

Hope that's will help someone.


Get data from database I'm running Drupal 7 site on WAMP Server!

I'm using below code in a custom block to get data from the database :

$result = db_select('event', 'x')
  ->fields('x', array('address'))
  ->execute()
  ->fetchAll();
foreach ($result as $value) {
  print_r ($value);
}

Event is the name of node we use

Every time I try to reload the page, I get this message :

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

When I check WAMP PHP error log, there is nothing in it about it !

Any idea ?

Update :
Now is see I get this error :

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.event' doesn't exist: SELECT x.address AS address FROM {event} x; Array ( ) in eval()

I understand that it mean it can't find the table, but why ? I found it like that in every example on the internet !

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

Above error is Drupal specific error, to get more details about this error you need to go to Drupal Logs. You can access Drupal Logs by navigating to "Admin => Reports => Recent Log Messages". These logs are provided by Database logging Module in Drupal Core.

Updates:

  Event is the name of node we use

In Drupal Nodes data is stored into node table and not table named with content type. Check out getting started guide about node. You've to check node table to get all nodes where type is event.

To fetch nodes you can use EntityFieldQuery API. Check example on How to use EntityFieldQuery. And to fetch any fields value, check Programmatically get field values.


No URLs in dashboard After installing Drupal I cannot use the dashboard menu because none of the URLs are found. I cannot google my way to find a solution to this so.

Check that the .htaccess file exists in the Drupal root. Sometimes people unzip/untar or copy paste Drupal directories and this file is excluded by some operating systems and file transfer programs.

Drupal 7 .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess?h=7.x

Drupal 8.2.x .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess

This is usually the cause of what you report.

Otherwise, this could be an issue with how Apache or IIS is setup to serve your Drupal site. Since you can really get in the weeds with server configurations such as Apache, it is recommended you use something like Acquia Dev Desktop or DrupalVM to install and run a Drupal site locally, so you can sidestep issues and run a local site under generally accepted best practices for a LAMP stack tuned for Drupal.


How can I programmatically get the theme name? In Drupal 8, is there a way to figure out what theme you are currently using in a module?  I need to get the name programmatically within the code of a module.

Using the theme manager is the proper Drupal 8 way of getting information about your theme.

\Drupal::service('theme.manager')->getActiveTheme()

A general rule in drupal 8 is look for the manager (/handler) service.

** Note: as Neograph734 pointed out, \Drupal::service('theme.manager')->getActiveTheme() will return the active theme object. If you want to get the theme machine-name then use \Drupal::service('theme.manager')->getActiveTheme()->getName()


Difference between hook_services_services and hook_services_resources I'm doing this tutorial to get familiar with the concepts of the Services module. In that tutorial, you implement a custom service for the Services module. Therefore it uses hook_services_services. But there are other tutorials (e.g. An introduction to Drupal 7 RESTful Services) that use hook_services_resources for the same thing. So what is the difference?

The first article is incorrect, there is no hook_services_services() (at least not according to any documentation for the services module, nor in my experience).

The correct hook to use is hook_services_resources(). See the docs/services.services.api.php file included with the module for full details.


How to add Drupal Coupon discount for selected category or item only? Project:    Commerce Coupon
Version:    7.x-1.0-beta7

Hi,

We are using drupal percentage coupon module for our websites and its very good.We have a request from customer where they need to exclude coupon discount for selected item/category.Reason they have a category which is having already discounted items.So now they need a feature where they can exclude coupon applying for those items.

Can we do this with existing module?

Thanks

You you can do it by adding new RULES. If you are using Percentage Coupon then you must have a rule in the list of rules list named "Calculate coupon with percentage amount".

Clone this rule & add more conditions according to your need like "Order contains products of particular product types" or "Order contains a particular product".

Its totally upto you to use conditional based discount and disable the default coupon redeem rules.


maintenance theme on every page On every page, maintenance theme is getting applied along with the user login boxes below the page after logging in. This is the state of the site which was handed over to me. I think this exists from a long time and no one gave importance to this issue.

This is my body tag obtained from inspect element (Chrome)

body class="marinelli html front logged-in no-sidebars page-newmain toolbar toolbar-drawer admin-menu" id="maintenance-page" style="padding-top: 65px;">

Please help me with this issue.

edit:
Uncaught TypeError: $ is not a function
    at marinelli:133
This is the information obtained from inspecting element.
It seems to be present in CDATA.. Where can i find CDATA?

    //grab all header rows
    $('th').each(function (column) {
        $(this).addClass('sortable').click(function () {
                var findSortKey = function ($cell) {
                    return $cell.find('.sort-key').text().toUpperCase()+ ' ' + $cell.text().toUpperCase();

Debugging is the art of removing all possible reasons why some unexpected/undesired issue arises ... so make sure your site is NOT in maintenance mode ...

To do so, navigate to admin/config/development/maintenance and ensure that "Put site into maintenance mode" is NOT (repeat: NOT) checked.


Location module should lookup address before saving This question is related to Adding geo location content to node.
I'm trying to get a location saved to a node. The Location module supports this, but I don't like the workflow of this module.

It does the look-up after the node is saved, but I would rather do the location look-up before the node is saved, e.g. by having a look-up button that, when pressed, queries Google, updates the gmap, and lets the user see the location before saving and not afterwards, which causes troubles, if the input address couldn't be found.

Do you have any idea on how to address this issue?

This doesn't help you with the Location module, but OpenLayers will map the location before the node is saved.


"Order items" view displaying removed items (variations)? I'm dynamically removing items from cart with this function:
  static function _remove_product_variation_from_cart($variationId) {
    $orders = \Drupal::service('commerce_cart.cart_provider')->getCarts();
    if (empty($orders)) {
      return 0;
    }
    $items = reset($orders)->getItems();

    foreach ($items as $item) {
      $quantity = $item->getQuantity();
      $itemVariationId = $item->getPurchasedEntity()->id();
      if ($variationId == $itemVariationId){
        foreach ($orders as $order) {
          $order->removeItem($item)->save();
        }
        return $quantity;
      }
    }
    return 0;
  }

And during checkout process it's all fine - removed items are not displayed. But page:
/user/user_id/orders/order_id

is listing also removed items (that's view "Order items"). Sum (order total) is correct however.
On other hand i.e. view "Checkout Order Summary" is returning order items correctly (without removed ones).
Am I removing cart item wrong way or something? Why is this happening?

foreach ($items as $item) {
  $quantity = $item->getQuantity();
  $itemVariationId = $item->getPurchasedEntity()->id();
  if ($variationId == $itemVariationId){
    foreach ($orders as $order) {
      $cart_manager = \Drupal::service('commerce_cart.cart_manager');
      $cart_manager->removeOrderItem($order, $item);
    }
    return $quantity;
  }
}
// return 0; <-- not necessary, functions don't have to always return.


Filter date + between dates is not possible In a view I show content that contain some fields and an entity reference.

In the Fields part of the view I have a field (Vervaldatum) like this.

The Vervaldatum field is a date field. I would like to have a "Vervaldatum between […] and […]" filter, but when I add a filter and select the Vervaldatum field, I get this.

I was hoping to get "between […] and […]" in the operator field, but no luck. It's like the field is handles as it is a text field, but the in the previous screen it's clear it is a date field.

These are the operators that I can use.

I followed the following steps using a Date field and got the intended result:

Firstly add your date field as a View filter

I left the configure date filter settings as default here

Configured the "greater than" exposed filter

Configured the "less than" exposed filter

Exposed filters appear correctly

Those are the exact steps I followed to get the two exposed date filters. Hope you come right!


Xdebug: What Drupal values for "Project URL" & "Index File" will NetBeans accept for a new Configuration? I just slept at a Holiday Inn last night and watched this Vimeo Tut on Xdebug. I'm experiencing trouble with a Views plugin and wish to "step into the Matrix" to find where the error is occurring.

In NetBeans each project is set up with a default URL and template file. These are set from File >> Project Properties -- Configuration (New). I have Netbeans and Xdebug working. The project default is the site home url and the top [drupal_root/] index.php file. I'm guessing if I make a new configuration of "Project URL" and "Index File" then Netbeans will open the project and focus my debug session to this area of Drupal. But so far the urls and index pages I'm selecting--Netbeans doesn't like.

I want to debug between the Edit View Page URL and the Configure Item URL. The error occurs between these two pages,

http://mysite.local/admin/structure/views/view/drag_test

And when I click on Draggableviews: Weight (asc) (under Sort criteria), the resulting non-JavaScript "configure item" page [*] displays the errors at the top,

http://mysite.local/admin/structure/views/nojs/config-item/drag_test/page/sort/weight

I'm guessing the views template, views-ui-edit-item.tpl, is what I want. Netbeans of course wants an index file, but in Drupal that's the top page.

What Drupal values for "Project URL" & "Index File" will NetBeans accept for a new Configuration?

[*] FYI. In case you're not immediately familiar with what a non-JavaScript Edit View Page is, remember how it was in Drupal 6 with options at the bottom of the page? Only in D7 options display on a new page when JavaScript overlay is off. (^_^)

The trick to target a specific page using NetBeans and xDebug is to use Arguments.

File >> Project Properties >> Run Configuration
Project URL: http://hellofrom.local/
Index File: index.php
Arguments: q=admin/structure/views/view/post_drag/edit/page_1


How to costumize the input fields but only in the page /user? I want to create a particular style with css for input style in the field of login, register and request new password.
The css if i see it width firebug is only one and i must adding a type only for the form of the /user page, but not for all page that containes form.
Thank you for help!

Check out the classes added to the opening body tag in the HTML. It will help you narrow down styles to just that page.

I know one of my D6 sites, there is a class in the body tag 'page-user' so you can use some CSS such as...

body.page-user .form-text {
  /* Add styling */
}

Inspect the HTML and style as necessary. :o)


When saving an updated node, does the update operation clear all caches? Just want to confirm when a node is updated, the update operation clears the complete cache table or the updated node related cache contents. Is this right?

There is only one line about clearing cache in node_save():

// Clear the static loading cache.
entity_get_controller('node')->resetCache(array($node->nid));

It only resets entity-related cache. Caches related to another nodes, caches like boost and so on are left untouched, unless specifically cleared by other module's actions in node or entity saving hooks.


Show only nodes in a view which have the same value of a text field (field_phone_number) I have a content type "ABC" with the "telephone" field (field_phone_number) added to it,
and I already have on my website around 1K nodes of this content type "ABC".

I want to display a table view on every node of type "ABC", displaying the title of all other nodes that have the same
"telephone value" as the content type being viewed.

I have tried to use the EVA module but with no success.

This is what I have done so far:

Create an EVA View that show: "content" of type: "ABC".
Add all the field that I want to display.
EVA Settings:

Entity Type: Content
Bundles: ABC
Arguments: Check the "Use tokens from the entity the view is attached to" and add: "[node:field_phone_number]"

Add contextual filter: "Content ID" with provide default value: "Content ID from URL"

Results:

A table view displayed on every node with only the node itself is displayed inside the table !!!! (Not what I need)

For example:

If lets say i have 12 nodes that have the same phone number value: "123456789".
What I am expecting to see is a view table displaying all the title of those 12 nodes every time I visit the page of each
and every node of those 12 nodes.

Usually doing the above by using an entity reference field as the comon value between nodes is very easy, but the problem is that I do not have an entity reference
field in commun between the nodes, rather I have the "Phone Number" field which is obviously it is not of type "entity reference".

Any help ?

Thank you,

You're on the right track with EVA. To list sibling nodes based on common taxonomy terms or entity reference fields you can just use Views configuration, but if you need to filter based on a different common field EVA is the way to go.

You did everything right except for the last step - you don't need Content ID Contextual filter, you're not comparing nodes, you're comparing Phone number fields! And the argument you set for EVA is the phone number, so that is the information you need to include there.

Add a Contextual filter for the phone field, you can configure it:
    When the filter value is NOT available
    Display contents of "No results found"
    When the filter value IS available or a default is provided
    Specify validation criteria
    Numeric (or whatever is applicable in your case)
    Hide view (if it doesn't validate)

That should list all the nodes that share that field, including the node you're currently viewing.

If you want to exclude the current node from that list you need to add another Contextual filter, this time it will be the Content ID one:
    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
    Content
    [ABC]
    More
    Exclude

That one will exlude the current node from that list.


How to get node title using this query on template? Im building a custom filter in Drupal 8 based on some queries.

I got this already, here im filtering by values on body:

$query = db_select('node__body', 'n')
                            ->fields('n')
                            ->condition('n.body_value', "%" . $searchWord . "%", 'LIKE')
                            ->condition('n.bundle', 'mycontenttype');
     $getList = $query->execute()->fetchAll();

Then i pass the variable to the Twig:

return [
            '#filters' => $getList,

In the twig im doing:

{% for oneItem in filters %}

But im unable to get the title of the node here, what im missing?

You shouldn't do queries like like that. You should use EntityQuery. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/function/QueryInterface%3A%3Acondition/8.8.x and EntityFieldQuery to search Content Type for text and select matching Nodes
EntityQuery will return the nids. Then use the node storage's loadMultiple to get the node themselves. Typically something like Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids)
I would expect the Node title would be gotten in your loop with {{ oneItem.title }}.
If that's not working I suggest installing and enabling the devel module, and sticking {{ dump(filters) }} in your custom template to investigate the structure you're getting


How do I add conditional validation? I have field collection. The problem is that one field is depended on select list.

When I choose type "job" from select list then company field should be required for that collection. Otherwise company field should be completely omitted in validation.

Update:

I tried to add my own constraint validator but with no effect and I don't have errors on that.

function job_market_user_entity_bundle_field_info_alter(
  &$fields,
  \Drupal\Core\Entity\EntityTypeInterface $entity_type,
  $bundle
) {
  if ($entity_type->id() == 'field_collection_item') {
    /* @var Drupal\field\Entity\FieldConfig $company_field */
    if ($bundle === 'field_jmu_working_experience') {
      $company_field = $fields['field_jmu_company'];
      if ($company_field) {
        $company_field->addConstraint('JobTypeConstraint');
      }
    }
  }
}

Constraint

namespace Drupal\job_market_user\Plugin\Validation\Constraint;

use Drupal\Core\Annotation\Translation;
use Drupal\Core\Entity\Plugin\Validation\Constraint\CompositeConstraintBase;
use Drupal\Core\Validation\Annotation\Constraint;
/**
 * @Constraint(
 *   id = "JobTypeConstraint",
 *   label = @Translation("Job Type", context = "Validation"),
 * )
 */
class JobTypeConstraint extends CompositeConstraintBase {

  /**
   * @var string
   */
  public $message = 'Company field is required for Job working experience';

  /**
   * {@inheritdoc}
   */
  public function coversFields() {
    return ['field_jmu_type', 'field_jmu_company'];
  }
}

Validator (I added violation just to check if it's invoked - no effect yet)

namespace Drupal\job_market_user\Plugin\Validation\Constraint;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 *
 * Supports validating company depended on job type
 */
class JobTypeConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;

  /**
   * {@inheritdoc}
   */
  public function validate($entity, Constraint $constraint) {
    $this->context->buildViolation($constraint->message)
      ->atPath('field_jmu_company')
      ->addViolation();
    return;
  }

  /**
   * Instantiates a new instance of this class.
   *
   * This is a factory method that returns a new instance of this class. The
   * factory should pass any needed dependencies into the constructor of this
   * class, but not the container itself. Every call to this method must return
   * a new instance of this class; that is, it may not implement a singleton.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The service container this instance should use.
   *
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('entity_type.manager')->getStorage('user'));
  }
}

You can use the States API to make a field visually required, visible/hidden and so on.

One simple example from https://randyfay.com/states

  $form['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name=student_type]' => array('value' => t('High School')),
      ),
    ),
  );

There are UI modules to configure this, like https://www.drupal.org/project/conditional_fields, but I think none is ported to D8 yet. So you have to form alter it in.

Also, keep in mind that this is UI only. You still need to implement corresponding server-side validation.


How to hide 'add to cart' button on content type full view? How to hide 'add to cart' button, on full mode view of a specific content type?
It has to be done on condition if product is purchased for this content type.

I tried to add custom field template but for add to cart button could not find the right template name. I also found out the field name which displays add to cart "field-product-ref" but the template field--field-product-ref.tpl.php is not working.
Need help in either identifying correct template name or any other approach which is correct?

You could use devel_themer module. After enable the module, a checkbox appear on left bottom of the window then, select the checkbox now you could find the template name after click the add to cart button...


views project management module I'm having a hard time understanding Views and Entity Reference in the context of the Project Management modules.

I have created Project and Task Content types. For each of the Tasks I have chosen a Parent Project. I installed PM Gantt, but it does not list more than one project. I am trying to create a view to simply list all projects followed by that project's associated tasks, if any. Some projects will not have tasks.

How can I do this?

Problem solved!

In Format/Settings set Grouping Field 1 to Parent.


Display main menu expanded in footer, drop down in header I'm trying to show the Main menu in two places, once as a dropdown menu at the top, then again in the footer as a fully expanded (non-collapsible) set of links. I'm using the Superfish module to handle the top menu, and Menu Blocks to place the menu in my footer region. I'm using D7 and am sub-themeing the Bootstrap theme. Ideally, I'm looking for a way to simply output the Main menu as a very simple unordered list of links, without any of the dropdown classes or scripting applied to it. Where would be the best place to do this? I tried overriding theme_menu_link but that didn't seem right (since I can't figure out how to get the region.)

We use the menu_block module for this - it lets you create unlimited menu blocks and control menu depth and other options.

This module provides configurable blocks of menu links with advanced features not available in Drupal 8 core.
Drupal 8 core allows you to display blocks of menu links starting with any desired level of a menu and limited to any desired depth.
And this Menu Block module provides additional configuration so you can choose to expand all menu links with children or to root the menu tree to a specific menu item.
The Drupal 7 version of this module provides all of these features since Drupal 7 core does not have any of this functionality.

So I just noticed you're already using menu_block. You can add multiple_menu blocks - you should simply be able to add a new menu_block for the main-menu on your site and use that one in the footer.


How to give default today date value in exposed filter? I am using exposed filter condition for date field in views.

I want to see the data in view by current date as default ..for that i am trying to give date field should be default by today date  and when i click on date filter and select on previous date i should see the previous data..

Is this possible by filters.

Yes it is possible.

Choose the date field in Filter Criteria section in Views
On the RHS of your date filter settings, you will see a section to enter a default relative date (refer screenshot)
Choose 'Enter a relative date' & enter the relative date as 'today'
Apply the filter & Save the view


TinyMCE image float, automatic set margin I'm using TinyMCE as WYSIWYG editor. When I set the floating of an image to "left" or "right", I want to set a right- of left-margin with CSS automatically. So the images has only a gap between img and text.

When I just add a margin to the IMG, there's a at all sides...

If the styles WYSIWYG button shows image right or image left try applying that and save your edit. If that applies ok you can use Firebug to see the CSS class it adds to the image and just alter the css rules to your needs.

Or else, you can supply your own css styles to a wysiwyg profile. They are typically of the form:

wysiwyg_option_name=css_class_name

for example:

ImageRight=img-right

you then make an image right class in your themes css file:

.img-right { padding: 0 0 5px 5px; }

I believe both TinyMCE and/or the WYSIWYG module both support these features.


Why did Views just jump from 3.8 to 3.10 (what happened to 3.9)? There was a security advisory issued for Views yesterday, but the new version is two ahead of the last (3.10 to 3.8).  What happened to 3.9?

The Views release page doesn't list a 3.9, or a reason why there is no such version.

Is this some new security rule I don't know about?

I can't say exactly what's happened in this particular case, but:

It's fairly common practice to do a double release in the case of security updates. Core for example, does this every time, although I couldn't find a reference to the practice right now.

Let's say you've released version X.Y.

Working on X.Y + 1, you've made some number commits on top of X.Y. Now you find a security problem in X.Y, and need to address it. You can now quickly rush out X.Y + 1 along with your additional feature work, and the security fix.

However, your new feature work isn't as well tested as it should be, because you hadn't prepared for a security emergency release. So although it might function perfectly well, likely, your work is "more buggy than usual".

Also, big sites are likely to be careful in upgrading versions, they'll need to take their time testing the site, making sure everything keeps working.

Any delay in the security update process is bad however, so we'd really like to be able to help people upgrade as soon as possible.

So what can we do? We can take the security only fix, and make a separate release of only that.

In this particular case, it looks like the feature release was done first, and then the security release. If I wanted to security patch my 3.8, I would have to pull out the diff between 3.9 and 3.10 and apply it. I could then take my time upgrading to the real 3.10.

If you look to Core for a similar example, check git log 7.31..7.32, which will show you that "SA-CORE-2014-005" was fixed on October 15th, however, the later release, 7.33 (git log 7.32..7.33) will contain commits from both before October the 15th and after. Gits history was re-written, such that the security update alone ended up in the next release, and any additional work then went into a new release. This requires more git trickery, but further lowers the bar for upgrading. In the case of SA-CORE-2014-005, this was important. Not so  much in the case of the Views issue, which was minor.


Assigning a page title to forms created with the form API FAPI I have a moule called newsl witch display a page containing a form.
I would like the way to specify the page title.
Is it with drupal_set_title() ? How to call it ?

if your page url http://site.com/my_page

you can use

function hook_page_alter(&$page)
{

    if(arg(0)=="my_page")
    {
                 drupal_set_title("Ahmed");
    }
}


Facet API : How to change some behaviors like having input radio instead of checkbox I need to change some default behavior from the facet API.

I am searching for documentation about the hook from the Facet API module, but I have not found anything for now, except a very good tutorial about Apache Solr and Facet API.

I downloaded the Facet API bonus module because I thought it would help me.

There are some very good features like Rewrite facet items via callback function, but it seems it only works for the markup; I can't change the input.

function custom_facet_facet_items_alter(&$build, &$settings) {
  dsm($build);
  dsm($settings);
  if ($settings->facet == "field_produit_dev_durable") {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);
    }
  }
}

I tried to use the Devel modutle o see the content of the variables build, and setting, but there is nothing interesting for me.

So I need two things

Understand how to change the checkbox input
Understand how to remove the count number aside the Yes or No

I made my module and use this, but weirdly it doesn't remove the number.

$build[$key]["#markup"] = drupal_strtoupper($item["#markup"]);

I used the fist tutorial I linked at the beginning of my post, but I found a problem I don't understand.

When I used my code on two different facets I got an error:

  An illegal choice has been detected. Please contact the site administrator.

My code is the same code shown in this article, but I replace the select field with a radio field. I think there is a conflict between the two form, when I validate.

What you're doing to change the markup should just work, here's a working example I have from a project that does just that:

function foo_facet_items_alter(&$build, &$settings) {
  if ($settings->facet === 'my_facet') {
    foreach($build as $key => $item) {
      $build[$key]["#markup"] = drupal_ucfirst($item["#markup"]);
    }
  }
}

I can confirm that it works as expected.

As far as switching the select for a radio, the error you get is pretty common and you're probably not removing/adding extra Form API options that aren't allowed for one of the types.

Radio buttons behave a bit different than selects, you might not be able to just switch the #type and have it work, if this is still relevant, please post the code you're using to alter that form... thanks!


Content types on "Add Content" randomly re-sort themselves Does anyone know why sometimes the content types on "node/add" in the admin will list differently every so often?

Example, say I have Article, Job, Page, Product, Resource, Webform. Sometimes they are listed alphabetically (preferred), but I just noticed after creating some content, some of the items are out of order - Drupal 8.2.7.

You can check in which order the content types are loaded from the configuration storage with drush:

drush ev "print_r(array_keys(\Drupal::entityTypeManager()->getStorage('node_type')->loadMultiple()))"


Simple category with drupal commerce not showing to anonymous users I followed this guide https://drupalcommerce.org/user-guide/setting-product-catalog and now I have a nice simple category page, but not visible to anonymous users. I tried changing the roles to marking all three options but no luck.. Any suggestions?

Here are some tips:

Set all checkboxes in People -> Premissions : Product-> View any product of any type
or If you are using any contextual filter in views configuration be sure that arguement exists in category page;


CCK Field with two values? Is there a way to have a CCK Field have two values for one input?

For example, a field called 'Sodium' and two values, '190mg' and '8%'- first being the amount, second being % of daily value.

If not, whats the best way to achieve this?

Edit:

The best solution I am looking for would be sets of Fieldgroups, and each row having 3 inputs. Label | value (required) | value (optional) - so, Sodium | 190mg | 8%

Take a look at the CCK multi group options, which are only a part of CCK 3.0+. This functionality allows you to combine multiple base fields into one field grouping. See http://drupal.org/node/119102 for the long history on how this came about.

I actually can't find good documentation on using it, as CCK 3.0 is still only in Alpha, so unfortunately you'll just have to play around with it some.

The other option is to write your own CCK field type, in which there is no issue creating multiple inputs for one field. The upshot is that you can definitely achieve this using your own custom field, the downsides are you are writing custom code (which is nice to avoid) and it's not as flexible as the multigroup options built into CCK 3.0


How to let user add multiple sub-content fields in the main content? If I want user to create a main content which can be able to add multiple sub-content for example
I wanna do apartment renting website. User have to create the apartment details which contain these fields; Title, Description, Address, Facilities etc.
As 1 apartment usually have multiple different units, user have to add their available units in the apartment node which contain fields; Unit title, room size, bedroom, bathroom, price. And they can add many units as they want.
The question is
 what module should I use? Can I use Organic Group module or something simpler then that?

I'm new for Drupal, learn by myself from scratch, anyone please point me the direction.

If apartment is one content type, and unit is another content type, you can use entityreference module to reference units in apartments. You will create in apartment content type - entityreference field with unlimited values, type of referenced entity would be unit content type - user will be able then to add as many units to his apartment as he wants.

You can even create a view of entity reference display, and use it for selection of available options in your entityreference field.

http://www.lullabot.com/blog/article/entityreference-multiselectors - also something about multiselector widgets for entityreference field.


How to access past DrupalCon website that requires password? I want to browse DrupalCon websites to learn stuff from past DrupalCon.

Below is partial list:

Chicago 2011    March   http://chicago2011.drupal.org/
Copenhagen  2010    August  http://cph2010.drupal.org/
San Francisco   2010    April   http://sf2010.drupal.org/
Paris   2009    September   http://paris2009.drupalcon.org/
Washington, D.C.    2009    March   http://dc2009.drupalcon.org/
Szeged  2008    August  http://szeged2008.drupalcon.org/
Boston  2008    March   http://boston2008.drupalcon.org/

However, a lot of them (e.g Copenhagen, D.C, Szeged, Boston) require user and pass to login. Not sure why some Con are open to public, some are closed.

Is there a way to obtain an account to access them? or Is there an alternative way to find content of those DrupalCon?

Thanks.

The reason they're password-protected is due to a critical security vulnerability in the version of Webform run on those sites. There's an open issue about it, and only the DrupalCon sites updated to a secure version of Webform are allowed to remain up.

In order to gain access to the ones that are still in lockdown, I'd comment on that issue to see what you can do to help get them updated. Otherwise, you can use the Internet Wayback Machine to access Archive.org's cached copy.


Can I render a region of my drupal site on a non-drupal site? Here is my situation.

I'm in the process of implementing Drupal as the primary CMS for a large site with hundreds of pages. But until the data input into Drupal can be done (which will be an ongoing process over months), I'd like the older "non-drupal" pages to at least be faked into looking like they are part of the same site. Basically I just want to tack onto the old pages, the new drupal header and footer (which are independent regions).

I was wondering if there is a known way to show a region from your drupal site on a regular php page? Such as a simple drupal "region rendering function" or something?

ps. The navigation has dropdown menus so iframes are out of the question.

Any constructive insight into how I should approach this would be helpful. Thanks.

You can try Web Widgets module to embed.

  Create dynamic snippets of your Drupal site that users can copy and
  paste to their websites.

  Supported widget styles: iframe, inline, UWA or Google Gadgets.
  Build a view and make a widget from it.
  Embed any other web site content in a widget with a simple widget API.

also look in to Embed widgets module.


How to save the previously selected option in the selection box, the default value strays Please help to understand what the problem is. I created a field Select to list in the comments to type of material field values I needed my, I redefined options list in the Custom Module

$query = db_select('node', 'n')
        ->fields('n', array('type', 'uid', 'title', 'nid'))
        ->condition('n.type', 'brigada_type', '=');
     $result = $query->execute();
     $brigade_list = array();
        foreach($result as $value){
             $brigade_list[$value->nid] = $value->title;
        }
        $form['field_select_brigade']['und']['#options'] = array(0 => t('- Select -')) + $brigade_list;

After I select a value from the list and create a comment I check it, and then only published but during the inspection the default value strays.

before

after

Solved the problem yourself with the help of code. It was necessary to create a handler instead comment_form_submit and create in him the values of a variable_set of my field value, so, I create custom field.

    function comment_author_form_comment_form_alter(&$form, &$form_state, $form_id){
           if($form_id == 'comment_node_zayavka_form'){
             $query = db_select('node', 'n')
                ->fields('n', array('type', 'uid', 'title', 'nid'))
                ->condition('n.type', 'brigada_type', '=');
             $result = $query->execute();
             $brigade_list = array();
                foreach($result as $value){
                    //if($value->uid == $user->uid){
                     $brigade_list[] = $value->title;
                    //}
                }
                $form['field_select_brigade_1'] = array(
                    '#type' => 'select',
                    '#title' => t('Select brigade'),
                    '#options' => $brigade_list,
                    '#description' => t('Please select the team that was sent to you with reference to this application.'),
                    '#required' => TRUE,
                    '#default_value' => variable_get('comment_field_brigade_selection'),
                );
        $form['#submit'] = array('comment_author_comment_form_submit');
        }
function comment_author_comment_form_submit($form, &$form_state){
        if(isset($form_state['values']['field_select_brigade_1'])){
              variable_set('comment_field_brigade_selection', $form_state['values']['field_select_brigade_1']);
            }
        }


drush_get_commands() does not return Feature Drush commands I am expecting that drush_get_commands() will return all drush commands including from modules such as 'feature', but it is not when called within my Drush custom command. How to retrieve all drush commands available for the current drupal instance including ones provided from custom modules? Thank You

It is important to remember that drush_get_commands() is sensitive to the bootstrap level that your command has reached.  You must have bootstrapped a Drupal site before Drush commands associated with modules in that site are available via drush_get_commands().  There are several requirements for this to be true.

You must have selected a Drupal site when you ran your custom Drush command, either by using a site alias (e.g. drush @mysite), or via commandline options (e.g. drush --root=/path/to/drupal --uri=mysite.org), or by setting your current working directory to the same directory that contains the settings.php file for your site.
Your custom command must declare a bootstrap level that is high enough to bootstrap a Drupal site.  For example, DRUSH_BOOTSTRAP_DRUSH is not sufficient, but DRUSH_BOOTSTRAP_FULL is.  If your command has not bootstrapped to a high enough level, you may call drush_bootstrap_max() to finish bootstrapping the selected site.
Drush commands will only be loaded for enabled modules.

If you do all of these things, then you should see all commands for all modules when you call drush_get_commands().  If you don't, try drush cc drush to clear the commandfile cache.

(As a side note, do not use drush_get_commands() as a way to call other Drush commands from your custom commandfile.  Instead, use drush_invoke_process().)


Entity without translation I want to make entity in Drupal 8 called cash that store only numeric value (integer or float). I think, that entity not need translation.
Is it possible for us to create custom entity without language/translation?

@IgorTengab
An entity in Drupal 8 needs translation to be enabled to be translatable

For example by going to /admin/structure/types/manage/ENTITYNAME > language settings > enable translation

For more info look here

But for your purpose perhaps a light-weight alternative would be to create a custom entity https://www.drupal.org/docs/8/api/entity-api/create-a-custom-content-entity


Improve D8 performance to access a custom REST controller Context

I'm currently upgrading a site from Drupal 7 to Drupal 8.

In the D7 version, there was a custom "proxy" module which served back-end services. Requests starting with a /service prefix, such as http://my-drupal-domain/service/service-name?service-args, were redirected to a custom index.php inside a D7 module. This alternative index.php called the minimal Drupal code needed : includes and drupal_bootstrap(). Then, the custom module's function handled the request, sometimes using Drupal native functions (to manipulate users for example) and passing it to the target service. Finally, it returned the service response to the client.

Now I want to migrate this to Drupal 8.

I managed to code a custom REST controller, using a custom route :

my_module.rest_services:
  path: '/service/{endpoint}'
  defaults:
    _controller: '\Drupal\my_module\Controller\ProxyController::index'
  methods: [GET, POST, PUT, DELETE]
  requirements:
    _access: 'TRUE'

The ProxyController, which extends Drupal\Core\Controller\ControllerBase, is basically the same code that handled the requests in the previous site, converted to the OOP-way of D8.

Initial problem

My problem is that, using D8 routes and Symfony2 components, the response time for any request increase proportionally with the number of concurrent users compared to the D7 version. For 20 users, this latency is +1s with D8 than with a D7 minimal bootstrap... That's huge! (see chart below, for the exact same call to D7 with a custom minimal bootstrap and D8).

Is there a way to bypass some of D8 code to redirect requests directly to my controller ? Some sort of "minimal D8 bootstrap".

Or a way to improve D8 routes performance ?

Edit: need to cache file parsing

I just discovered Drupal 8 is not the only responsible for my performance loss! during the request handle process, in my module's code, I read and parse a YAML configuration file, using file_get_contents() and Drupal\Component\Serialization\Yaml::decode(). But Drupal does not cache the value by default : the file is read and parsed on each call. With 20 concurrent users, it can take up to 600ms...

I need to find a way to tell D8 "Read this config file once, parse it and cache the content so you don't have to read it again unless your cache is cleared".

Given I did not have many responses, I answer myself to share the bits of explanation and solution I found.

Below the performance loss sources I've identified :

The use of D8 full bootstrap, including modules loading, routes resolving, etc.
Reading and parsing a YAML config file each time the module handles a request

And the solutions I applied :

Custom D8 minimal bootstrap

Based on this post and the default D8 index.php, I created a custom Bootstrap in my proxy module :

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\my_module\Controller\ProxyController;

chdir( $_SERVER['DOCUMENT_ROOT'] );

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$container = $kernel->getContainer();

$response = ProxyController::create( $container )->index( $request );
$response->send();

$kernel->terminate($request, $response);

Like it was made in the D7 version, I redirected all request with the /service prefix to this file.

PHP config instead of YAML

I didn't find a way to load and parse the YAML config file once and cache the result.
(I'm still interested if someone know how to do that by the way)

So i converted the config file content myself into PHP, put it into a .php file and
use include instead of file_get_contents() and Yaml::decode().

Result

You can see here the response time obtained combining the 2 solutions above.

I assume the remaining perf loss is due to the use of OOP instead of procedural PHP. But if I want to stick to the D8 standards, I can't do much about it...


multilingual support I would like to create a content type in Drupal 7, which is available in both Italian and English. This is why I enabled multilingual support in the options of publications that allows me to choose the creation of each new node language.
But...How do I then change the choice of language in which I see the node in the web pages?

You need i18n module. It gives you a possibility to display a language switcher block on the front end.

Also check Localization update module for automatic update of translations.