Form Submission values in Hook Form Alter method I wrote a custom method to do some set of operations when a webform is submitted and that is working fine. However I need to access some fields values that has been submitted in the Webform.

The fields in the Webform are: 'phone' , 'emailid'. I need to access these variables in the method custom_example_some_function. I tried playing around with some arrays, but that didn't worked out.

function custom_example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_22') {
       $form['#submit'][] = 'custom_example_some_function';
  }
}

function custom_example_some_function($form, &$form_state) {
// Do something
// echo $phoneNumberFromForm;
// echo $emailidFromForm;
}

You'll find submitted values in $form_state['values'], eg

$foo = $form_state['values']['bar'];


How to showing Created time in node teaser? I'm using Omega for theming and I want to show created date time in teaser Article.

I found this <?php print format_date($node->changed, 'article') ?>

But I don't know where to put it.

Any Help?

To print date add this <?php print date('d M Y', $node->created); ?>

The output of this will be something like: 12 Dec 2014.

You can change 'd M Y' part for different output, take a look at date() function.


Creating multiple URL aliases for the same node with their own context I want to solve the following problem with Drupal 7 solely using existing modules and without any extra code.

I have a contenttype called 'News'
I create a news item and assign a taxonomy term called 'Sport' and a taxonomy term called 'Entertainment'.

Now I want Drupal to create two URL aliases, namely:

http://www.domain.com/news/sport/title
http://www.domain.com/entertainment/title

I want to assign different blocks based on the path with context.

Is this possible without custom code? And if custom code is neccesary how would I proceed?

This should be working using the Rules and Pathauto modules. There's already a similar question that is answered: How to automatically generate multiple aliases for one node?


Is it possible to have placeholder text on a view filter with type date_text? I've got an exposed filter on my view that allows users to specify a date, and I want to specify a placeholder for this text field.

I've tried doing this using the following code in a hook:

$form['field_start_end_dates_value']['value']['#attributes'] = array('placeholder' => array(t('Search')));

(I know this is in the correct hook as I'm successfully altering other form elements within the same form)

I've var_dumped the form variable, and I'm getting the following output for the date filter:

[field_start_end_dates_value] => Array
        (
            [#tree] => 1
            [value] => Array
                (
                    [#title] =>
                    [#type] => date_text
                    [#size] => 20
                    [#default_value] =>
                    [#date_format] => j M Y
                    [#date_label_position] => within
                    [#date_year_range] => -3:+3
                    [#process] => Array
                        (
                            [0] => date_text_element_process
                        )

                    [#prefix] =>
                    [#suffix] =>
                    [#attributes] => Array
                        (
                            [placeholder] => Array
                                (
                                    [0] => Specify Date
                                )

                        )

                )

        )

This looks right to me, but I'm not seeing the placeholder on the front end.

I've tried flushing the cache multiple times, and loading the page without JavaScript enabled.

What am I doing wrong?

You are doing it wrong way

Form alter doesn't work here.
This is how it can be achieved:

It depends on which date element you are using
There are few hooks available

hook_date_text_process_alter()
hook_date_popup_process_alter()
hook_date_combo_process_alter()
hook_date_select_process_alter()

I am showing for hook_date_text_process_alter()

/**
 * Implements hook_date_text_process_alter().
 */
function MYMODULE_date_text_process_alter(&$element, &$form_state, $context) {
  if ($form_state['complete form']['#form_id'] == 'views_exposed_form') {
    //dpm($form_state);
    if ($element['#id'] == 'edit-field-appintment-date-value-value') {
      $element['date']['#attributes']['placeholder'] = t('Demo placeholder');
      //dpm($element);
    }
  }
}

For Other text elements
Below is the correct example of adding a placeholder to views_exposed_form to any other text field but date field can't be done like this.

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#attributes'] = array('placeholder' => array(t('Your Placeholder')));
}

Hope this helps


List options without typing on autocomplete Is it possible to show options when user clicks to the input field instead of showing after typing at least one matching character?

Autocomplete starts showing the options after user types one character but it is hard to guess for new users what's the possible options for related field.

A possible solution is to show the field as a select list and then use the chosen module to get the functionality of searching through the options.

From the module's description:

  You can force enable/disable Chosen for certain field widgets: Select list (for both list and date fields), and Select (or other) list. If you have a field using one of these widgets, in the field settings, you will find a Apply Chosen to the select fields in this widget? option with three values: Apply, Do not apply, or No preference (which will fall back to using the automatic application).


Output the total number of rows in a view Does anyone know how to show the count of the results of a custom view?

You can add a custom section to either the header or footer to do this.

Edit the view / display.
In the center section, click Add next to Header or Footer.
Choose Global: Result Summary.  Add it where you need it.
Then, edit the textarea to be the format that you need.  There are a bunch of tokens available for building up the numbers.
Preview the view, and then Save if everything is OK.


block visibility snippet restrict path I use the following snippet to restrict who can see a block inside admin pages. Can you help me add the restriction of a path /cart* for non admin users into this snippet?

if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

I am assuming the logic is:

Display this block only on pages with a path beginning with cart/*,
And only when the user has `access administration pages` permission

If so....

if (arg(0)=='cart' && arg(1) && user_access('access administration pages')) {
  return TRUE;
} else {
  return FALSE;
}

If you want it displayed on path cart all by itself as well, just remove the && arg(1) from the above and then it will work on cart in addtion to cart/foo and cart/foo/bar etc.

If, however, you want it only on cart/oneargumentonly, you can add in && !arg(2).

ADDITION/CORRECTION:

if (user_access('access administration pages') || (arg(0)=='cart' && arg(1))) {
  return FALSE;
} else {
  return TRUE;
}

while return FALSE if the user can access administration pages regardless of the path OR the path is cart/* regardless of any permissions.

So, if my logic is right now, if the user can access administration pages the if is "short circuited" and returns FALSE.  Otherwise, if the user doesn't have this permission, it continues on and if the path is cart/* it returns FALSE.  Otherwise, since we already know the user doesn't have the access administration pages permission it returns TRUE for any other path.

FINAL?

if (user_access('access administration pages') || arg(0)=='cart') {
  return FALSE;
} else {
  return TRUE;
}


How to remove the zip code field from the checkout page? I have a Drupal 8 website with Drupal Commerce 2.x. I want to disable the zip code field in the checkout page. How can I do this?

Address modifications should be done on the Address module level, not on the Commerce level.

You can disable the zip code for a specific country by subscribing to the AddressFormatEvent and removing the %postalCode token from the $definition['format'] string. A str_replace('%postalCode', '', $definition['format']) should do it.

You can find an example event in this blog post.


How do I add additional view modes for a node? I am creating a custom content type. By default, nodes support only two view modes (full and teaser):

function mymodule_view($node, $view_mode)
{
    if ($view_mode == 'full') {
         $node->content['#theme']= 'my_full_node_view_theme';
    }

    if ($view_mode == 'teaser') {
          $node->content['#theme']= 'my_teaser_node_view_theme';
    }
    return $node;
}

I want to add some other view modes for this node type, like:

small_box
small_box_with_user_pic
big_box

and want to render the node with code like this:

$node = node_load($my_nid);
$output = drupal_render(node_view($node, 'big_box'));

Any suggestions?

first we have to add additional view modes with hook_entity_info_alter

function customuserblog_entity_info_alter(&$entity_info) {
     $entity_info['node']['view modes']['blog_post_big'] = array(
        'label' => t('simple big  teaser'),
        'custom settings' => TRUE,
      );
    }

// we may attach additional theme functions or templates and add variables with hook_view

function customuserblog_view($node, $view_mode) {
  if ($view_mode == 'blog_post_big') {
   // add some additional variables for template
    $node->content['#theme'] = 'custom_blog_big_teaser_view';
  }
}

// in our hook theme

customuserblog_theme(){
    return array(
      'custom_blog_big_teaser_view'= array(
          'render element' => 'form',
          'template' => 'custom-blog-big-teaser-view',
       ),

    );
}


Dynamically Theme Boolean Fields I am trying to dynamically display boolean fields into columns based on their value.  So for instance these 10 boolean fields on my node, if marked 1, I want it to theme it so that they show up in a column to the left titled Completed, and if marked 0, a column to the right titled Not Complete.  I have tried using template.php and field.tpl.php but I am getting very lost.

I'd like to do this on the field node being viewed (not using Views) as a custom dynamic field formatter that applies a different css class to the field div.  That or in the theme layer using some php magic.

Okay I think this might be what you're looking for:
http://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_display_alter/7

I'd throw that function on your template.php, enable the Devel module, then use kpr() to print the variables to the screen and go from there.


Change JSO(N) parameters that have been set by another module I am trying to override parameters that have been set by another module. The other module uses drupal_add_js() to set the parameters.

 $settings = array('color'=>'red','type' =>'round');
 drupal_add_js(array('MyData'=>$settings),'setting'));

This adds a JavaScript object to the drupal.settings data object. I want to override that in another module, and I don't know how. It seems to always "ADD" to the array and NOT override it.

The following code doesn't work.

$js = drupal_add_js(null,'setting'); //<-- get the JS
unset($js['setting'][1]['MyData']['color']);
drupal_add_js($js,'setting');

 $settings = array('color'=>'PINK'); // <- Change red to pink
 drupal_add_js(array('MyData'=>$settings),'setting'));

How can I do what I am trying?

You should try this

// Get all the current javascript information
$current_js = drupal_add_js(NULL, NULL, 'header');

// Filter the information down to just the settings.
$current_js_settings = $current_js['setting'];


Create nodes unlimited times I've been trying to ajaxify the node creation form, the purpose?

Save the node and remains in the node creation page (Done)
If the user clicks the save button again save a new node

The second point is not working yet because once the Ajax request is sent again the previous created node is updated.

I tried with:

function saveAjaxForm(&$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AlertCommand('Saved'));

  return $response;
}

It works, but other #submit callbacks in the form aren't called again.

How can I "execute again" all the submit functions in the form?

For some weird reason the Ajax response wasn't updating the form_build_id value and the request takes it as the same form, so I added a new Ajax Command:

function saveAjaxForm(&$form, FormStateInterface $form_state) {
  $old_form_build_id = $form['#build_id'];
  $new_form_build_id = $old_form_build_id.rand();

  $response = new AjaxResponse();

  $response->addCommand(new UpdateBuildIdCommand($old_form_build_id, $new_form_build_id));
  $response->addCommand(new AlertCommand('Saved'));

  return $response;
}

It solves the issue.


Reset user password without using "Forgot password?" I know that in Drupal 7 I could reset the user #1 password via code.

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$newhash = user_hash_password('newpass');
$updatepass = db_update('users')
  ->fields(array('pass' => $newhash))
  ->condition('uid', '1', '=')
  ->execute();

(user_hash_password() doesn't exist anymore in Drupal 8.)

Alternatively, I could use the following code.

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once DRUPAL_ROOT . '/includes/password.inc';
$edit['pass'] = 'newpass';
$account= user_load(1);
user_save($account, $edit);

What is the equivalent code for Drupal 8? What API should I use for this purpose?

It's easier these days:

$account = \Drupal::entityTypeManager()->getStorage('user')->load(1);
$account->setPassword('new password');
$account->save();


file_scan_directory() takes about 10 seconds to execute Using xhprof I noticed that file_scan_directory() takes more than 10 seconds to execute when front page loads. Why should it take such a long time?

This is the output of xhprofile:

It sounds like you're affected by a known issue in Drupal 7.

  Most probably, you are hitting Avoid re-scanning module directory when multiple modules are missing. It happens if you have some missing modules in your installation. Try to check your system table:

SELECT name, filename FROM system WHERE type = 'module' AND status = 1 ORDER BY filename

  And clean-up any modules that are still enabled but missing from the filesystem.

  Overall, Drupal 7 is way more resource friendly and scalable then Drupal 6, other than some unfortunate regressions like this one.

Looking at those functions, it does look like it's missing a module or maybe a single file of a module. Have a look at drupal_get_filename(), it does call the drupal_system_listing(), which calls this function if it can't find the requested file. Add a dpm(func_get_args()) right before it calls drupal_system_listing(), that should tell you which file it isn't finding.


Install a module in Linux I am looking to download and install a module using the Linux command line.

How can I do this?

You can install Drush (see Installing Drush on Ubuntu or How to install Drush server-wide in less than one minute); after, you can install a module with drush:

to download a module

drush dl modulename

to enable the module

drush en modulename

Also, you can use wget to download the module, and make a directory inside the modules directory (in this case the modules directory is /home/youruser/public_html/sites/all/modules/).

    wget http://ftp.drupal.org/files/projects/modulename-6.x.tar.gz
    mkdir -p /home/youruser/public_html/sites/all/modules/modulename
    tar -zxf modulename-6.x.tar.gz -C /home/youruser/public_html/sites/all/modules/modulename

Enable the  module in "Administer > Site building > Modules."


Need webform with list of items, price, and total Not sure that webform can do this, BUT my client sells yachts. They want a webform on the site that lists all of the boat options (a check-list) a potential customer might like to have and creates a subtotal at the bottom of the list as the customer checks items on the list.

The way it works: A visitor is interested in buying a boat so they go through the list and check(box) the item/s they want, and as they check the items a subtotal is calculated at the bottom of the list. Then the webform is submitted to the company sales to someone that will contact the potential customer to continue the sales effort.

This should be something like a spreadsheet, but the list cannot be changed (only the checkbox next to each item). The subtotal is affected only by the items on the list that are checked.

This might better be done by something like ubercart, but seems ubercart would be overkill.

Does anyone have ideas how this could be done (or if it cannot) with webforms, OR if there is a better way, please?

cFusch

You can try Webform Calculator, I know it has checkbox support. You can set values for fields, then calculate the total amount at the end of webform for the submission.

  Provides a formula webform component for computed values, where you
  can enter a mathematical calculation based on the other fields. E.g.,
  create a formula field with value formkey1 * 0.1 * formkey2.


Drupal 6: How to create a special case for searches on a limited set of single symbols (such as @ and ! and " and : )? For the system I'm creating pages for some symbols have special functions. I have pages/nodes with those symbols as their title. @ and ! especially at issue because they appear in two different contexts (entirely different meaning in each), so there's two pages for each of them '@ (context A)' and '@ (context B)'.

When a user uses the Drupal Search, and searches solely on '@', those nodes should be in the search results. So far, I'm getting 'You must include at least one positive keyword with 0 characters or more.' when searching on the symbols, even after reducing the required word length to zero (I forced cron to run after doing so).

Does Drupal 6 strip out all or some of the symbols from the search text?

After playing with this for a while it occurred to me that since there's very few of these the approach might be to simply create a special case for them in the search. Is there a hook I could intercept in a module to handle the special cases? What's the best approach here? :)

Added Information:

To clarify, 'context A' and 'context B' were merely made up examples. the real thing would look more like: '@ (primitive)' and '@ (prefix)'. A search on '@' should turn up both, since the site has no way of knowing which (prefix or primitive) the user needs to know about.

Taking a fresh look at the problem this morning, I took a stab at finding out how to create a module to solve it. I think the search terms are run through 'check_plain', stripping it down to just text (no symbols).

Turns out that a module providing the hook_search_prepocess hook can override the text used by the indexer and the search. So I put together a module in which my hook does a replacement of '@' with 'atsign', which appears to solve the issue. Also means I can set the minimum word size back to '3', as long as my replacement text is 3 or more characters.

I now have a sites/all/modules/searchfix/searchfix.module file (and corresponding .info file), with the following function in it:

function searchfix_search_preprocess($text) {
    return str_replace("@", "atsign", $text);
}


How do I keep data without using sessions Is there a way to store data for separate users in Drupal without using sessions. I have previously used Drupal varibales. But it didin't work because the variable gets updated for every user (So whenever I access the variable it shows the last users details). I can't use sessions because I have a horizontally scaled server, so when the server is changed the sessions will be deleted.

Is there a way to do this exactly as the sessions but without sessions? I need to save users data in the browser temporarily.

If you don't need your data server side, you could use cookies, using user_cookie_save. Or store your variables in window.localStorage (it's HTML5, see here for browser support) in your own javascript code/behavior, like :

function storePersistentValue() {

  //Check whether local storage is available or not

  if (window.localStorage) {

    window.localStorage.MyKey = "HTML 5 features";

  }

}

function getPersistentValue() {

  //Check whether local storage is available or not

  if (window.localStorage) {

    var text = window.localStorage.MyKey;

  }

}


Execute system cron manually How to execute system cron manually via drush or drupal UI?

To execute just the system_cron() hook, the easiest way is with drush

$ drush php-eval 'system_cron();'

This will start a PHP process, boostrap Drupal, and run the input.  Note that this will run everything that this hook does, in addition to the file cleanup, including garbabe collection on the various database tables with ephemeral data, like {cache}, {batch}, {flood}, etc.  There isn't an individual function in Drupal 7 that just handles the file cleanup.

Also keep in mind that when you run drush like this, you are running as the user who you logged in as.  This user may or may not have persmissions on the files and tmp directories in order to delete files.

You could copy this code into your own script and then do

$ drush scr cleanup-the-files.php


LoginToBoggan and user registration password to allow users register with password and email verification at the same time I am using the LoginToBoggan module to enrich the account functionalities. In its settings there is a Set password field; when it's not checked anonymous users can't choose their passwords in registration form but they can receive verification emails.
I need both functionalities: email verification and set the password field in registration form.
I found the User registration password module which allow users to choose password in the registration form.
The problem is when I create a new account. The user can login with the chosen password, but I need they first verify their email.
So the process must be like this:

Anonymous users register and choose their password in the registration form
They receive a verification email
They click on the link given in the email to activate the account

The problems I have now are the following.

Users can log in after registration, even if they didn't click on the link sent via email
The link in the email is a kind of reset password link and not a link to verify the email link

Is there a possibility to fix this and allow users to choose their password in registration even if they still to verify the email they use for the site?

You could use https://www.drupal.org/project/registration_role to auto assign a different role (as in other than authenticated) to users who register.
https://www.drupal.org/project/autoassignrole this one offers a little bit more functionality.


Check if empty region failed I try to check if my sidebar second if empty. If it is not empty, I add a class col-md-8 on my section-main.
To check if the sidebar is empty I use this code in the page.html.twig template of my custon theme:
{% if page.sidebar_second and page.sidebar_second is not empty and
page.sidebar_second|render|striptags|trim is not empty %}

My problem is that sometimes the sidebar second if considered as empty but it is not. In the sidebar second, I have a views block that the content depends on the current node taxonomy or book id. The query to get the content of this views block if altered in my_custom_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) function.
When I checked for sidebar_second in page.html.twig, the content of this block is always empty, but if I have another block in sidebar_second (so the column is displayed), this block has actually some content and is displayed.
So to check if my sidebar is really empty or not, I tried to check that in the my_custom_theme_preprocess_page() function in my_custom_theme.theme, like this :
  $rendered_sidebar_second = \Drupal::service('renderer')->renderRoot($variables['page']['sidebar_second']);
  $with_sidebar_second = !empty(trim(strip_tags($rendered_sidebar_second)));
  $variables['with_sidebar_second'] = $with_sidebar_second;

Then , in my page.html.twig, I check the variable with_sidebar_second to know if sidebar_second is empty o not. This gives the right results, but induces a problem for assets : PHP Exception LogicException: 'A stray renderRoot() invocation is causing bubbling of attached assets to break.. Using renderPlain() gives the same result. Using render($variables['page']['sidebar_second'], false) does not give the good result.
Is there a solution to have the good result for the sidebar_second and have all assets too ?

In theming the use of render() is correct, you can't use a different render method. The problem is that many blocks are placeholdered and you can't determine at the point the page template is rendered in which context the placeholdered block might be rendered in future. Probably then with a different user logged in because blocks cached per user are placeholdered by default.
The code in your question thinks the region is empty because striptags removes placeholders which usually are formatted as HTML tag.
You can change this at the expense of cache performance by adjusting the cacheablity of the blocks involved or customizing the auto-placerholder condition site-wide.
See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


Webform simplenews component styling I am creating a Newsletter field for just one component to include email only for newsletter subscription, but I need a way to style both the input field and the submit button to be inline, i.e side by side rather than above each other like typical forms.

You can make use of the arrange fields module.

  This module lets you drag-and-drop the fields of any CCK content type,
  Webform, or almost any other form in Drupal into the positions you
  would like for editing. This makes it super simple to have forms with
  inline fields, which you can change at any point. Tab indexing is also
  updated, so no matter how you arrange the fields, the users can still
  tab through them easily. And, you can now add arbitrary bits of HTML
  markup-- labels, images, HR's, etc.


Problems with SQL Syntax using Left Join and OR I need some help with my SQL. I've got the following code but it's returning multiples of each item and I don't understand why. When I only include the first Left join it returns results as anticipated...but when I add a second LEFT join and include the 'OR' in the WHERE part of the query it returns multiples of the same resources names. After my query I explain more about the context.

$result = db_query("
SELECT rn.field_resource_name_value,
       rn.entity_id,
       el.field_experience_level_value,
       rl.field_role_value,
FROM {field_data_field_resource_name} AS rn
LEFT JOIN {field_data_field_experience_level} AS el ON rn.entity_id=el.entity_id
LEFT JOIN {field_data_field_role} AS rl ON rn.entity_id=rl.entity_id
WHERE el.field_experience_level_value='$level' OR rl.field_role_value='$role');

This code is part of a recommendations page where users get resources displayed based on their answers to (we'll say two for now) questions on a form. The questions are radio buttons and ask for their experience level and role. These values are saved in session vars that I've already put in $level and $role respectively so those are values like 'Novice' and 'Writer'.

What I'm trying to accomplish - and what the PHP code that displays results (not shown, but below the query) does - is display a list of resources that match the experience level and role the user selected on their form. Obviously I only want each resource to display once, not five times for each. Also, if a user selected both Novice and Writer, let's say, I'd want any resources returned that had EITHER role set to writer OR exp. level set to novice, not necessarily both (although that's fine too).

I have a resource content type that stores it's values in various tables. So each resource title will store its name in the table field_data_field_resource_name, and the matching experience levels (each resource can have multiple levels - some are good for both Novices and Experienced users for example - these are set as list fields in the resource content type). The matching experience levels are stored in another table (ref. in the sql above) and the matching roles, likewise, are ref. in a separate table. The only thing all of them have in common is the entity_id field which matches them all to the resource name...hance the SQL above.

Pfew. So given all that background. Can some knowledgeable SQL expert advise me as to what is going on here?

Thanks!

The answer it appears is to use the GROUP BY statement in my SQL right after the WHERE clauses. So, the following:

GROUP BY rn.entity_id, rn.field_resource_name_value

The returns just one entry for each field resource name.


How to prepopulate a node reference field (checkbox) On a node/add page I have a node reference. The widget type is "checkboxes" and I'm using the "View used to select the nodes" feature to show up to 5 checkboxes on the node/add page.

I would like to prepopulate a checkbox with the prepopulate module.

The checkboxes use this HTML name value:

name="field_tribe_content[und][18824]"

Usually prepopulate works by adding this to the url, but it doesn't work in this case.

?edit[field_tribe_content][und]=18824

There is some info in the issue queue and I have also tried

?edit[field_tribe_content][0][nid]=18824
?edit[field_tribe_content][0][nid][nid]=18824
?edit[field_tribe_content][nid][nid]=18824

How can I get it to work or what else could I do to preopulate those checkboxes?

Take a look here:

Prepopulate checkbox [#checked]

I have also been searching for a solution on how to do this.


How to get taxonomy term name/label from a field? Ok, so I'm trying to populate a field based on the selection of a taxonomy term. I've mainly got it working thanks to this stack exchange article
use Drupal\taxonomy\Entity;

function module_entity_presave(EntityInterface $entity) {

  if($entity->bundle() == "node_type"){
    $bread_slice = $entity->get("field_taxonomy_term")->getString();
    $bread_butter = "- Additional Text for Reasons";
    $bread_title = $bread_slice." ".$bread_butter;
    $entity->field_title->value = $bread_title;
    //save is done automatically
  }

}

The issue is that, the resulting code doesn't print the name/label of the term, but instead the tid. So, it ends up showing as "757 - Additional Text for Reasons" I barely know any php, but I know enough to get around. I suppose my issue is the fact I'm not getting the correct value from the taxonomy array, yet I'm unsure how. I've tried finding the correct value using some twig debugging, {{dd(data.taxonomy_term)}} but all the values for it show null. Please point me in the direction of how to solve this?

The field only stores term IDs. So either get the term ID and load the term from it or load the referenced entities directly.
/**
 * Implements hook_entity_presave().
 */
function MYMODULE_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {

  if ($entity instanceof \Drupal\node\NodeInterface && $entity->bundle() === 'MYBUNDLE') {

    if ($field = $entity->get('field_MYFIELD')) {

      if (!$field->isEmpty()) {

        $label = $field->referencedEntities()[0]->label();
        // dpm($label);
        // Code on...
      }
    }
  }
}

Consider installing Devel. It gives you some handy debugging helpers like dpm($some_var) to dump variables into core's status messages block so you can inspect them easily.


Drupal commerce custom discount I'm using the Drupal Commerce module.

I want to make a discount rule where if there are 3 or more products of type X, you get a discount of 40% on all type X products. I don't know how I can do this without affecting type Y. Can this be done by pricing rules?

If you're willing to make "products of type X" "products with taxonomy term X" instead, you could probably get away with using Commerce Taxonomy Conditions. With it, you can create a product discount that applies 1) if an order has a certain quantity of a taxonomy and 2) if the current product has a certain taxonomy term.

If that didn't suite you, you could model the correct discount/inline conditions from that code... ripping out the taxonomy bits and replacing them with Drupal Commerce product types.


How to redirect to search result page? I’ve activated the search form block on my Drupal home page.

When a user enters a keyword and presses search button, I would like to redirect to the search page result.

How can I do that?

function MyModuleName_form_alter(&$form, &$form_state, $form_id)
{
   if ($form_id == 'search_form_id') {
     $form['#submit'][] = 'MyModuleName_custom_serch_form_submit';
   }
}

function MyModuleName_custom_serch_form_submit($form, &$form_state)
{
  if(isset($_GET['q']) && !empty($_GET['q']))
  {
     $string_serch= $_GET['q'];
    drupal_goto("http://yourdomain.com/search?q=".$string_serch);
  }
}


Flag state as contextual filter in views Please help me and provide a little explanation about the following thing:

1) What I have:

a content type called "word"
a flag for this content type called "learned".
a view display with "word" nodes

2) What I want to achieve:

filter view results with "learned" flag state (to get only flagged, or not flagged, or all of them) for current user via contextual filter.

I've added a relationship on "Flags: Content flag" where i can limit results to those nodes, which are already flagged by current user. But honestly I don't understand how to connect this relationship with contextual filter to get a possilibily to receive different results basing on the flag state (flagged, unflagged, all).

Actually, I want to get the same result as if I use an exsposed filter on a Flag state. But I don't want to use an exposed filter as well as I'm using an ajax call to load this view display with predefined options.

Any help?

Not with contextual filter, in views I think it's posible with a normal filter (not exposed) since you have already the flag relationship, first add your flag as a field (don't display it if you want) then just filter your nodes with the flag status (flagged). Then you clone the view and change flag status on filter (now to unflagged)  and you will have an opposite view (non-flagged) content.


How to shift/change timestamp in a scheduled rule? A scheduled rule was triggered. Is it possible to change a date of the scheduled action? (programmatically or not) For example, the scheduled action will be triggered in 3 days but then you would like to change it for 1 day.

Yes, the timestamp of when the task is to be scheduled is stored in rules_scheduler db table, in date field. You can run a query like:

db_update('rules_scheduler')
  ->expression('date', 'date + 86400') // 86400 = 24 * 60 * 60
  ->condition('tid', $your_task_id)
  ->execute();


how to set a global variable that is referenced throughout the site? i'm trying to avoid programming and hoping i could do this with modules:

I have a classified ad's website which has about 100 categories where users can add an advert. The thing is these are all linked to a location. So i use two vocabularies- one of categories and one of locations.

I want to be able to allow the user to select a location when they first land on the site from a dropdown and then when the user moves through the site this is referenced. I have two specific use cases

When the user goes to add a listing, their location is pre-selected in reference to the one they already selected at the initial visit.
When the user returns they only see adverts relating to their town/city (consider them being already registered)

Ok. With next to no programming I would recommend trying to use the Session Cache API. This module allows for simple items to be stored in say a cookie, even for Anonymous users. You may want to try to use it directly, or use a module that already makes use of it, such as:

Views Global Filter, this module allows you to set an exposed views global filter your visitors fill out once -- and it's remembered for the duration of their visit. As they visit throughout your website your other views pages or blocks would query the existing saved off global filter values in cache and be shown the listings you want.


Why can't I debug twig templates with intellij idea? I can't get intellij idea to break on twig files. It is breaking on theme and module files fine. This means that xdebug must be setup correctly. I don't believe that it is caching as I've deleted the cache files

drush ev '\Drupal\Core\PhpStorage\PhpStorageFactory::get("twig")->deleteAll();'

The problem was that the twig cache path was not set for the project.

See https://blog.jetbrains.com/phpstorm/2019/05/twig-and-blade-templates-debugging-2/


Paging issue in views when implements node access I have created a content type called Details it is the collection of employees detail. And also I have created a Taxonomy terms called manager, employee, lead. Also I have created a field(as Taxonomy reference) for user profile to indicate whether she/he is manager or lead or employee. Now I want to put the restriction based on the user. I have achieve the restriction using my custom module. The codes are below:

    function my_module_node_access($node, $op, $account) {
  global $user;
  $user_obj = user_load($account->uid);
  if (isset($node->type) && ($node->type == 'details') && ($op == 'view')) {
        if (($user->uid == 0) || ($user_obj->field_user_company['und'][0]['tid'] != $node->field_company['und'][0]['tid'])){
            return NODE_ACCESS_DENY;
        }
    }
  return NODE_ACCESS_IGNORE;
}

The above code simply do, if the node taxonomy term, and the user field taxonomy term is same then he will perfectly access to the nodes. I got struggle with views. I have created a view to show the node title that can be access by the user. Manager has 100 nodes to view, in views settings I have enable the pager, 25 items per page to display. Pager splits into 4 page and shows correctly. But when comes to employee user he has access to 1 node only, but in views it still shows the pager in 4 parts.

function my_module_views_post_execute(&$view) {
  if (($view->name == 'views1') || ($view->name == 'views2')) {
        $nids = array();
      foreach($view->result as $key=>$result) {
          $nids[$key] = $result->nid;
      }
      $nodes = node_load_multiple($nids);
      foreach ($nodes as $node) {
            if (!node_access('view',$node)) {
                $key = array_search($node->nid, $nids);

                unset($view->result[$key]);
            }
        }
     }
  }

The views pager display must be changed dynamically depends on the number of nodes. Is anyone knows kindly show me a right path to achieve this???

hook_node_access() doesn't really do any access checks on node listings or views.

To get this to work you should look into implementing hook_node_grants() and hook_node_access_records()

That logic will be included in your views query so you could get rid of hook_views_post_execute()


Access callback called multiple times? I have this hook_menu implementation

$items['lablab/%level/%unit/%tab/%section/%exercise/go'] = array(
        'title'           => 'My lablab',
        'title callback'  => 'lablab_form_set_title',
        'page callback'   => 'drupal_get_form',
        'page arguments'  => array('lablab_form',1, 2, 3, 4 ,5),
        'access callback' => 'lablab_access_exercise',
        'access arguments' => array(5),
        'file'            => 'lablab.forms.inc',
        'file path'       => drupal_get_path('module', 'lablab').'/includes',
        'type'            => MENU_CALLBACK,
    );

And then in the access callback

function lablab_access_exercise($w_exercise){
    dpm($w_exercise->value());
}

Then when i enter the hook_menu page it shows me at least 4 dpms, is this normal?

the wildcard %exercise was returning several entities.


How can I reset my password in drupal7 I am new to Drupal and this forum.

My problem is that I want to reset my password in Drupal without logging onto my site, but I can only access user/password when I'm logged in.

I've searched a lot and haven't been able to find anything else.

Can anyone help me out?

If you have drush installed, you can reset your password from the command line using

drush upwd --password="givememypasswordback" admin

For more information you could see the link.


Form fields created via Ajax are missing element attributes I have a custom form with a date field and a series of textfields and number fields. The textfields and number fields are dynamically re-created via an ajax callback function that runs whenever the date field changes, because the default values of the textfields and number fields will depend on the value of the date field.

The form runs this function once upon loading, which works fine, it returns the $form object with all expected values in the fields.

However, whenever that same function is called again by the ajax trigger, almost all of the attributes of the dynamic fields are missing. The data-drupal-selector, id, name, and value attributes are gone. The default values do not appear. The for attribute of labels also disappears.

I have noticed that this is not true of table form API elements and only seems to affect input elements and labels.

Is this the expected behaviour? Is it avoidable?

Example:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['date'] = array(
        '#type' => 'date',
        '#ajax' => [
            'callback' => '::dateCallback',
            'wrapper' => 'wrapper',
        ],
        '#default_value' => date("Y-m-d")
    );
    $form['wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'wrapper'],
    ];
    $this->dateCallback($form, $form_state);
    return $form;
}

/**
 * Implements callback for Ajax event on date selection.
 *
 * @param array $form
 *   From render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current state of form.
 *
 * @return array
 *   Date selection section of the form.
 */
public function dateCallback(array &$form, FormStateInterface $form_state) {
    //insert logic to determine value of a variable called $field1

    $form['wrapper']['options'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('options'))
    );
    $form['wrapper']['options']['field1'] = array(
        '#type' => 'textfield',
        '#title' => "Field 1",
        '#default_value' => $field1
    );
    $form['wrapper']['table'] = array(
        '#type' => 'table',
        '#title' => t('Table'),
        '#header' => array("H1", "H2", "H3"),
        '#attributes' => array('class' => array('custom-table'))
    );
    //insert logic to generate table rows
    return $form['wrapper'];
}

(Note: In order to get ajax to work with date fields, as per my previous question, I had to apply a Drupal patch. However, I am pretty sure this issue is not related to this patch, as the problem persists even if I attach the callback to another form APi element like a Select dropdown.)

It seems like a good idea to invoke the callback in the form build to include the form elements of the callback in $form to allow the form builder to process these elements. But then you overwrite the same form elements that the form builder has processed with the unprocessed form elements when the ajax triggers the callback.

Solution: Move all form elements in buildForm(). Leave the callback empty, only return the wrapper part of the form.


How to change value a field of preproces I am new to PHP and Drupal. I have content type with a type list text field "Infraestructura". The values and labels are these:

agua | Agua de pozo
incendios | sistema contra incendios
electricidad |Electricidad

The quantity options is unlimited, is to say, the user can select unlimited options (Checkbox)
How I do to change the output for this field as image?
I need  that output for this field  show an image , example:

for: agua | agua =>
for: incendios | sistema contra incendios  =>
for: electricidad |Electricidad  =>

I'm thinking to do this using preprocess, but I not have idea. Could anyone help me please?
Here is another way to explain what I want to do:

You should preprocess the field output and add a class based on the value. Then to theme in css. It's a good idea to keep the images separate and business logic separate.

<?php

/**
 * Implements template_preprocess_field().
 */
function acTheme_preprocess_field(&$vars) {
  $element = &$vars['element'];
  if ($element['#field_infraestructura'] == 'field_infraestructura') {
    $value = $vars['element']['#items'][0]['value'];
    $vars['classes_array'][] = 'type-' . drupal_clean_css_identifier($value);
  }
}

?>

Take this qwith a grain of salt - I don't see the actual code and values in my debugger, but if you replace myfield_name with the name of the field, and mytheme with the theme name (all these machine names), then it should assign the classes based on the values.

Sadly, there may be some need of tweaking this code if some mapping does not fit - so, I hope you know at least some PHP to do that.

The output classes should be somehting like class="type-agua", and then you can theme it. You need to know css, of course - there are samples in the comments under your question.


How to (ab)use image effects to serve API generated images? I made code to add a custom effect using hook_image_effect_info() that does not alter the image for real. I'd like to serve an image from my own API instead, that has calls like myapi.com/img2123?w=25&h=88&watermark=true. I don't think that the code for a placeholder effect is relevant is it?

I'd like to use this because that way if I add an Image field to a content type I can choose a banner for example on every 'Article' content type.also I need to pass the parameter returned by the dimensions callback (set in the form callback of hook_image_effect_info()) to the GET request as an URL parameter.

I was thinking: could I use some node altering hook to change the uri that is parsed somewhere else in the program?

If you need some additional info, just ask. Thanks in advance.

If you are getting the image from another server/site you don't need an image field. If the link isn't going to change, you can store it in a text field and build a link like this

your_module_node_view($node, $view_mode, $langcode) {
    $url = $node->field_cool_image[LANGUAGE_NONE][0]['value'];
    //redefine field_cool_image to display your image
    $node['content']['field_cool_image'][0] = array(
        '#markup' = ''
    );

}

otherwise build the link when the node view is built.

your_module_node_view($node, $view_mode, $langcode){
    //whatever method you use to build a url
    $url = my_build_url($node);
    $node->['content']['my_cool_img'][0] = array(
        '#markup' = ''
    );
}


How to print the HTML content of the text field in Drupal 6 programmatically I am printing the $node->field_abc[0]['value'] in php code where node is node content and field_abc is text field .

How can I print the html format of the field in Drupal 6

You can use content_view_field

  content_view_field : Render a single field, fully themed with label
  and multiple values.

Code

$node = node_load('NODE_ID');
echo content_view_field(content_fields("field_example"), $node, FALSE, FALSE);

Reference

Print a formatted CCK field with PHP


SSD drupal performance improvement There are some VPS services that advertise that have SSD. Does it worth the extra money?

In a setup with varnish/nginx/php-fpm/apc/drupal/mysql, would SSD provide any significant performance improvement in drupal 7?

If yes, in which case scenarios?

I am managing a site that gets about 1000 unique visitors a day. Not sure how big your application is, but 1000 is enough to cripple a default drupal install.

I added the standard performance optizations, apc, etc, but found that memcache by far had the best result. My pages used to take 20 seconds to load. Now pages load instantaneously. If you have not tried that, I would see if that helped first before investing in the SSDs.


What to do if we want a input format for select options of a webform? I have a web form with select option field whose value is quite long. I cannot use css to configure this. I need to use input format so that I can break this option using HTML code. Is there any module or something?

Additional Info:
We don't have input format option in case of webform module's select fields. My value in select field option is quite long. I have three values like below:

  Session 1: PwC
  11:30am
  Sourcing Strategies for the Next Decade

  Presented by:
  Damon Paling, Partner, PwC China
  Anthony Tennariello, Partner, PwC New York
  Maytee Pereira, Director, PwC New York.

I would like show the user like this but this is not possible since we don't have input format (HTML) to select.

I recommend the chosen module.

https://drupal.org/project/chosen

Its goal is to make input element a little more user friendly.

See here: http://harvesthq.github.io/chosen/


Send data from a Drupal site to a web service Is there an existing module that sends data from any form from my Drupal site to a web service?

UPDATING my PROGRESS:

Ok, I decided to continue my project using cURL. I created my form that contains 2 fields: "Name" and "Phone" and a submit button. (All in my own module)

Then I show my code that I just did. However, when I see the web service. The shipping data, not shown. I did a debug and uh I realized that when running: "curl_exec ($ch)" returns me FALSE.

function mymodule_form_submit($form, &$form_state){
    $name = $form_state['values']['name'];
    $phone = $form_state['values']['phone'];

    $att = array(
        'name' => $name,
        'phone' => $phone
    );

    $attendee = http_build_query($att, '', '&');

    $url = 'http://[IP]/event/management/attendee';

    $headers = array('Content-Type: application/x-www-form-urlencoded');

    $userpasswd = 'user:pass';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $attendee);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
    curl_setopt($ch, CURLOPT_FAILONERROR, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $result = curl_exec($ch);
    curl_close($ch);
}

The params,in the web service, are: attendee['name'], attendee['phone'].
What is my error?

UPDATE 2: NOW with this code, the variable $result return me a bool(TRUE). That tell me that the data was pass to the webservice. But, when I see the web service, I see no records with the data that I supposedly sent.

Well, it probably depends on the type of web service you want to send data to, but there is this module, REST API Query, for REST web services (http://drupal.org/project/rest_api_query).

This week we needed to send an issue report form data from a Drupal site to a Redmine issue tracker, using the Redmine web API. We played around with the above module, but finally decided to do it in plain PHP, using CURL.

Here's the code we are using (inside the custom Drupal module we made), so you can get a general idea. You can easily adapt to your specific needs.

$url = {The API url here};
$userpasswd = {api-user}:{api-pass};
$xml = {XML payload};

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_USERPWD, $userpasswd);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$result = curl_exec($ch);
curl_close($ch);

UPDATE: There is a drupal core function that performs the same task, drupal_http_request. I guess it would be better to use that one, doing it the drupal way and all :-) I have not yet tried it out though.
http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request


Why does drupal commerce create an empty order for every anonymous user? Drupal Commmerce is creating an empty order for every single anonymous user in my website (over 13000 in just a few hours).

Users on my website have no direct access to the shopping basket, nor do they have any means of adding products to the cart, since for the moment, I'm only planning to use the Drupal Commerce functionality for specific users (i.e. I will create a product in the backend, then send the URL to the customer).

It doesn't seem right that so many orders are created for users who don't even have the shopping basket block in their page.

Why does this happen?

Is there a way to prevent it?

You can see in the screenshot how the empty-basket orders are being created for every anonymous user, this is slowing down the site!

There's nothing in core Drupal Commerce that would create an empty order for every anonymous session. Core Commerce will only create an order when an anonymous user adds a product to the shopping cart. This means some other module must be creating those orders for every session. I'd look to your contributed modules, especially if any are facilitating adding products to the cart via links instead of forms.


What does Rules token "node:unchanged" mean? I am on Drupal 7 and I am using the Rules module to do some stuff.

I must say that I am not very used to using this module; there are few questions that need answers, such as the use of the node:unchanged token.

For example, when I set a rule with a data comparison as a condition, I have to give the name of the referred field; then, there is either node:changed or node:unchanged.

I am quite accustomed to using node:changed. What does node:unchanged mean?

Terminology

"unchanged refers to the value before something (eg, a field of entity user or node) gets updated (the old value that it used to be).

"changed refers to the value after something (eg, a field of entity user or node) gets updated (the new value that it will become).

Examples

Have a look at my answers to these question for some typical usecases of it:

Monitoring field changes in custom content type
How to implement admin verification for selected user profile fields?
How to include only an updated custom field in an email created using Rules?
How to use Rules to email users when any field(s) is changed in a node (and include the unchanged/changed values for that field)?


Popup dialog window based on selection in radio select list? Use case:

A radio select list with Option A and Option B.

When User selects Option A, a popup appears with specific "A" message to verify the selection before User saves the page.

When User selects Option B, a popup appears with specific "B" message to verify the selection before User saves the page.

Suggestion on how to develop this? Hoping there's a module.

Since the popup appears as an immediate reaction to the user selection, this looks like a job for JavaScript or jQuery. Take a look at the jQuery Dialog user interface. And here is a tutorial on working with JavaScript within Drupal.


Views Eposed filter - proximity search, include content without a postal code I have a proximity search set up using gmap location by postal code. Using Drupal 7/Views 3.
The exposed filter allows the user to filter by (taxonomy)type and/or postal code.

This is what I need to Do: Include some content that will not have a postal code in all results. I already set up a view of this content (without postal code) to display as no results behavior.  but I would like to include this same content in all searches. How do I do this?

If you can not do it with the 'And/Or' option on the filters (accessed by clicking the little arrow next to the filters in the views ui). This is the best option.

Or you could use hook_views_query_alter to add something like "or where postcode = '' ".
I can not really go into detail of adding to the query as I dont know the structure of your query but you can take a look at the database api or search google.


Fast way to get translations of all installed modules I have a site with a lot of modules. Now I need the german translation (if available) of all this modules.

Is there a faster way than downloading and importing them one by one?

Use the Localization Update module, it will hold all your modules translated and up-to-date.

  Automatically download and update your translations fetching them from localize.drupal.org or any other Localization server.


How to add jQuery Datepicker option which accepts a function as an argument I have added a date_popup field to a form :

$form['arrival_date'] = [
  '#type'                => 'date_popup',
  '#title'               => t('Arrival date'),
  '#date_format'         => 'd/m/Y',
  '#date_year_range'     => '0:+1',
  '#date_label_position' => 'none',
  '#default_value'       => '',
  '#size'                => '10',
];

I want to add an option to run a function using the onClose option so my js is :

(function ($) {

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      $('#edit-arrival-date-datepicker-popup-1').datepicker('option', {
        onClose: function (date) {
          // date will have the new date or empty string if no date
          // has been selected.
          alert(date);
          // Do something
        }
      });
    }
  };

})(jQuery);

However the onClose event never executes.  If I remove the 'option' argument thus :

$('#edit-arrival-date-datepicker-popup-1').datepicker({

it does work, but my suspicion is that it is replacing the datepicker with a new one, rather than altering the existing options.

You have to ommit the 'option' parameter, the following modified version of your code worked for me:

(function ($) {

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      $('#edit-arrival-date-datepicker-popup-1').datepicker({
        onClose: function (date) {
          // date will have the new date or empty string if no date
          // has been selected.
          alert(date);
          // Do something
        }
      });
    }
  };

})(jQuery);


How to remove a unique key in an update hook I have a primary key and a unique key in my modules' schema.  I need to remove the unique key.

To remove an an index it is simple:

function draggableviews_update_7205() {
  if (db_index_exists('draggableviews_structure', 'entity_id')) {
    db_drop_index('draggableviews_structure', 'entity_id', array('entity_id'));
  }
}

There is a db_index_exists() function.  There is db_drop_unique_key() and db_add_unique_key() function, but no db_unique_key_exist().

How do I remove the unique key in an update hook?

All of the core schema classes (mysql, pgsql & sqlite) check for the existence of the constraint before actually dropping, so you don't have to check yourself. If you do you're actually doubling up on a DB op unnecessarily.

To cover all eventualities your code could look something like this:

try {
  if (db_drop_unique_key($table, $name)) {
    // Constraint was found and removed.
  }
  else {
    // Constraint was not found, nothing was altered.
  }
}
catch (PDOException $e) {
  // Constraint was found, but something went wrong, see $e->getMessage() for more info.
  throw new DrupalUpdateException($e->getMessage);
}

Incidentally, a unique constraint is treated the same as an index by the core schema classes, so db_index_exists() can be used to check for them too.


Like / Dislike Button I need to like AND to dislike contenttyps, but the total likes should be displayed as Likes - Dislikes. I tried to use the "flag" module and created two different flags (one for likes, one for dislikes) but this leaves me with two problems

I need to get the total count of the likes (likes - dislikes) within a view - how can I do this??
Can I disable the like/dislike button, if it was already clicked? So you can like and dislike but only once (no toggle).

You might be able to customize the excellent tutorial on the use of Ajax for Like and Dislike using voting API by Amitav Roy. His primary purpose is to show the reader how to use AJAX, but the code is solid and seems to suit your purpose.


How do I migrate the file attachments field from a content type? My Drupal 6 site has different content types, and there is a File Attachments field added to the content types. While migrating to Drupal 8.1, this field is not getting migrated, but the attached file is present in the files directory. While doing the migration, it is displayed that the "upload" module in Drupal 6 has migration path, yet it is not migrated.

How can I migrate the file attachment field to Drupal 8?

In Drupal 6, file attachments are considered enabled if the upload-module is enabled, and the variable 'upload_[content_type]' is true or not set. The latter could be the cause that your attachment fields are not being migrated.

There is an open bug report for this scenario, including a patch, at https://www.drupal.org/node/2829274


How to set individual fields permission on content type fields based on roles using field permssion I am using field permission module. I want some fields to be editable for other roles which I set using field permission module, but when I login as that user role I don't get the edit option on the node.

What I am actually trying to achieve is this:

I have created a content type with fields.
I want editor role users to submit pictures for that post.
They should not be able to edit other fields but just this.

Field permissions do not add permissions, but only take permissions away.

If a user is not allowed to edit a node, giving him the permission to edit a field won't work. Instead you must give him permission to edit all nodes (of a certain type) and deny access to all field he may not edit. (and yes that can be a struggle if you add fields in the future)


Search API view - Displaying items that doesn't meet Facets criteria I have a search api view where I display houses with number of bedrooms in each of the house, and I'm using facet api to create filter so that for example if I would click on "2" it would only display houses that have only 2 bedrooms in it.

But I would also like to below this view (or as part of this view) display other results that doesn't meet the criteria (and that are filtered out by facets) and I'm really stuck with how this can be done.

In addition I only want it to happen with "Bedrooms" but not with "Bathrooms".

I hope someone can help I'm really stuck with this issue!

** small update 26.09.2015 **

I'm trying to achieve that now by combining two views together using views attachment and having "views negate" filter to work on values provided by exposed filter.. so far no luck.

And views attachments are being displayed UNDER pagination, instead of after the normal results which is not what I ideally would want to have.

After that I'm planning to change the normal exposed filter into BEF with links and style them as facets...

Might be wrong place, but my query is related to retrieving improper data. I am using facet to filter the result its working fine. But if I use solr slop to retrive data all the  record are proper and then try to filter the record using another facet Sector then the result displayed in location facet is improper. e.g

Initially search for England, it retrieves all data of England record include location, Sector Cont type data.Location details are displayed in location facet block. But when I do deep filter using Sector facet(sector records are within location searched I.e. England) I get records from Scotland location too.. Scotland location is listed in the location facet along with England. Not knowing what is going wrong afteer using Solr slop as without it all the data retrieved is proper.


Is there a way to export a list of all pages and files? I received an email from a customer today requesting a list of all pages and files on their website. Since they are content administrators, I am about to reply with simple instructions for navigating the "Content" area since all the information they are looking for is there.

Is there a module or a tool of sorts that could help generate a list automatically of all the nodes within a site?

You can use Views Data Export

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS (or really simple HTML understood by Excel)
  Microsoft DOC
  Basic TXT
  XML

and export as CSV. I recommend you watch this video tutorial.

Your client can then view the CSV file in Excel.


Remove seconds in time picker How do I remove or hide seconds in the Drupal 8 time picker?

I removed the seconds from the daterange widget by setting the step attribute in hook_field_widget_WIDGET_TYPE_form_alter() to 60 (seconds)

function my_module_field_widget_time_range_form_alter(&$element, FormStateInterface $form_state, $context) {
  $element['value']['#attributes']['step'] = 60;
  $element['end_value']['#attributes']['step'] = 60;
}


Show Entity Reference items as table I have two Content Types (Country, City).
I want to display full contents of City in Country, so I did like this:
- create a field in World Content type
- set this field as entity reference (City).

Drupal print the two City contents in World successfully but I want put the city content in horizontal tabs.

I tried the module references_tabs, but it can put only one field reference at time.

How can I do so?

Thanks

According to the description of  the   References Tabs module

  This module allows to render nodes referenced via a node reference
  field in tabs, with node titles as tab titles and rendered nodes as
  tab content.

it is only support Nod referenced not entity reference ,you can see here  that it is not support entity reference , you can change your field from entity reference to node reference type.


How to use views achieve this I've two nodes Person and Mission. A Mission can contain many Person's. Now if I'm browsing Person node, then in right side bar block I want to show all Mission's associated with this Person.

Example:

Mission1 contains ( 1 field containing multiple values):

Person-A
Person-B

Now if I go and view Person-A then in a block I should see Mission1 as it is associated with it.

You can use a CCK "node-reference" field. This way you can "link" one mission page on all person pages. After you did this you can easily make a view that gets all persons that are in the mission node...

Maybe you can take a look at:
http://drupal.org/project/Relation


How to associate the last image from gallery to user's profile picture In Drupal 7  (Commons 7.x-3.46).

I've created a new content type, by which each user can upload images and build a personal picture-gallery.

How can I now associate the last-uploaded-image to the user's profile-picture?

Amodule-based solution is preferable. Is there a better way of doing this, ie without a new content type? Essentially I'm looking for a user-friendly way for users to upload and show their profile pictures.

Amodule-based solution is preferable. Is there a better way of doing this,
  ie without a new content type? Essentially I'm looking for a user-friendly
  way for users to upload and show their profile pictures.

I would like to recommend field_collection module as I already mentioned in the question's comments.

Step # 1: Enable field_collection module.

Step # 2: go to /admin/config/people/accounts/fields and add a new field named as User Gallery (machine name should be field_user_gallery) and choose field type as "Field collection" and save. Note that you can set the field cardinality as you like.

Step # 2: Go to admin/structure/field-collections and add a new image field named as Image (machine name should be field_image) and choose field type as "Image" and save. (It might already be added in the existing field list.)

Step # 3: Download custom module from custom_user_profile and extract to your module directory. Make sure extracted directory name is custom_user_profile and then enable it.

That's all. I hope it will work for you as works for me.


How do I reference a file field and node title from another content type & node? I need to add a link to a file, added through a file field on its own content type called "Document" from another content type and node call "plan information".

The idea is that the "document" nodes are displayed to provide access to a collection of "documents" throughout the entire site. This content type simply has a title and a file field. That cannot change.

What I need to do is to add a LINK to a user-selected document on the "plan information" content type that links the "document" to the appropriate "plan information" node as selected by the content manager.

On the "plan information" nodes, I want to simply create a UL of the document(s) attached using the title of the "document" node as the anchor text.

We've had a big problem with updating documents where associating the right "document" link on the correct "plan information" node has been problematic at best.

I've tried entity reference but couldn't get that to work. It would either bring in the entire document node, or nothing at all.

I tried node reference but it wants to behave in a similar way as the entity reference did, pulling in the whole node.

I tried field reference, but again, no success.

Most grateful for any guidance/insight on this.

Ok - I got it figured out.

All I needed was the entity reference field.

I then followed the steps in the article posted below which allowed me to then be able to attach my document entities to my plan info nodes.

https://www.ostraining.com/blog/drupal/entity-reference-view/

Then i was able to create a view of the plan info nodes by creating a relationship in views to the referenced entity on the nodes, then I had the necessary fields available to me as fields for my view, and that solved everything.


How to show a message to a list of article publishers using Rules? I am trying to send a simple message to each user in a list of particular users (article publishers) on the site, using the Rules module.

More specifically:

Event: After saving new content
Condition: Content is of type: Article
Action: Load a user list with views (using Rules Bonus pack - user list of article publishers)
Action: Loop (above user list)
Loop action: Show a message on the site

But with above configuration:

1) the only user who's getting the message is the current article publisher and

2) the message is displayed x times where x is the number of users in the user's list.

Apparently something is missing and/or the rule has mistakes.

Can anyone help?

The loop isn't checking for the current user, so it is showing a message for all the users in the list, like you describe.

You need to check that the current user is in that list.

To do so you really need the http://drupal.org/project/rules_conditional module.
It allows you to have conditions in actions.

So your rule would be something like this:

Event: After saving new content
Condition: Content is of type: Article
Action: Load a user list with views (using Rules Bonus pack - user list of article publishers)
Action loop: Loop (above user list)
  Conditional:
    If: Data comparison (Parameter: Data to compare: [site:current-user:uid], Data value: [list-item:uid])
      Action: Show a message on the site

However, if you say that the list of users is any user that has created an article, and this message is being displayed after a user creates an article, then you can be sure the user who just created the article is in the list of users who have created an article :)
So just show the message when an article is created. No other checks for users.


Populate a field on node creation I have a content type "abc". I have a field "listing id". I want this field to be prepopulate starting from  1 and autoincrement" on every "abc" node creation.

How can I do this.

It looks like you can use the Serial Field module to accomplish this.

From the Serial Field page on Drupal.org:

  Usage

  You can add a serial field to any type at admin/content/types ->
  manage fields. In the New Field form select Serial as the type of data
  and label and field name as your choice, and Save. No other settings.


Module that adds &nbsp after one letter words I'm Polish. In my language leaving one letter words at the end of the line is a mistake. I know i can deal with it adding &nbsp; after such words. Is there a module which takes care of it (eg. while saving the content to db)?
RtL

Traditional Drupal way is to use Text Filters. Here you have introduction text - it's for Drupal 6, but nothing important changed since then. Examples for Developers contains example filter. Use regex replace or other method from stackoverflow to make actual replacement:

preg_replace('/(?<=\b[a-z]) /i', '&nbsp;', $s);

All the rest you can copy-paste from Examples.


How do you implement a breadcrumb? I've tried to define a new breadcrumb override, but I'm still getting the site default.

I've created a custom module, foo_breadcrumb:

   - modules/custom/foo_breadcrumb
     - foo_breadcrumb.info.yml
     - foo_breadcrumb.services.yml
     - src/
         - BreadcrumbBuild.php

Here's the foo_breadcrumb.services.yml:

services:
    foo_breadcrumb.breadcrumb:
        class: Drupal\foo_breadcrumb\BreadcrumbBuild
        tags:
            - { name: breadcrumb_builder, priority: 100 }

Inside src/BreadcrumbBuild.php, I have:

<?php

namespace Drupal\foo_breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderBase;

class BreadcrumbBuild implements BreadcrumbManager {
    /**
     * {@inheritdoc}
     */
    public function applies(array $attributes) {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function build(array $attributes) {
        $breadcrumb[] = $this->l($this->t('Test'), NULL);
        $breadcrumb[] = $this->l($this->t('Test2'), 'test');
        return $breadcrumb;
    }
}
?>

I started working off the only writeup I could find on Drupal 8 breadcrumbs, but the thing is it appears to be using an older version of the PSR-4 autoloading that is no longer in place (for the record I'm on 8.0.0-dev-beta3), and so I went by how all the other modules work in the codebase.

Now I'm fairly certain this correct to get the module to load; however I'm not sure if

class BreadcrumbBuild extends BreadcrumbBuilderBase

is correct. The problem is that the old tutorial I linked to mentions extending from BreadcrumbBuilderBase, but the more current docs don't seem to mention it and I wonder if it's out of date - and how I should do this.

Likewise, I don't really understand what the services.yml file is doing in this regard, there's no documentation anywhere for this.

Here we go again.  These answers are mostly right. One thing you can't forget about is "cache tags" and "cache contexts".

I was setting up a taxonomy term on a node as a breadcrumb.

I got it working with advice from this post, but then I clicked around and noticed the same breadcrumbs on every page.

Long story short, make sure to set some cache contexts and tags.

Here's my service in a gist: https://gist.github.com/jonpugh/ccaeb01e173abbc6c88f7a332d271e4a

Here's my build() method:

/**
 * {@inheritdoc}
 */
public function build(RouteMatchInterface $route_match) {
  $node = $route_match->getParameter('node');
  $breadcrumb = new Breadcrumb();

  // By setting a "cache context" to the "url", each requested URL gets it's own cache.
  // This way a single breadcrumb isn't cached for all pages on the site.
  $breadcrumb->addCacheContexts(["url"]);

  // By adding "cache tags" for this specific node, the cache is invalidated when the node is edited.
  $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

  // Add "Home" breadcrumb link.
  $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

  // Given we have a taxonomy term reference field named "field_section", and that field has data,
  // Add that term as a breadcrumb link.
  if (!empty($node->field_section->entity)) {
    $breadcrumb->addLink($node->field_section->entity->toLink());
  }
  return $breadcrumb;
}


Filter out nodes with the same title in views I have an event system which uses the date repeat entity to clone repeating events and another section which uses the similar by terms module to create a view of events related to the article.

However I want to filter out the repeating events, is there a way of adding a condition that if the titles match then ignore them?

Consider looking at the Views Distinct module to do this ... Here are some details about this module (from its project page):

Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.
For any given field, including "Global: Text" fields, you can optionally mark the field as filtered ("Filter Repeats") or aggregated ("Aggregate Repeats"). All rows with the same value in that field will either be removed as duplicates (filtered), or aggregated in-line.
The "value" of the field as used for filtering or aggregation can be taken pre-render (fastest and totally cacheable), or post-render (after any rewrite rules or other transformations have occurred). Post-render actions are a bit slower (the View must be re-rendered, though the query is not re-run), but also work with Global fields, like Global: Text w/rewrite rules.

If this doesn't work for you, or for some reason you cannot / do not want to use this module, then consider any of the alteratives suggested by Sumit Madan ... (+1 !).


What will be the url to show all content type posts? OK i have created a content type. But what will be the url that will show the list of all posts in specific content type?
Basically I want to make a link or a menu item that will show all posts in specific content type but off course paginated.

You will have to use the Views module to create list filtering for a specific content type.

The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Traditionally, Drupal has hard-coded most of this, particularly in how taxonomy and tracker lists are formatted.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content.
You need Views if:

You like the default front page view, but you find you want to sort
it differently.
You like the default taxonomy/term view, but you find you want to
sort it differently; for example, alphabetically.
You use /tracker, but you want to restrict it to posts of a certain
type.
You like the idea of the 'article' module, but it doesn't display
articles the way you like.

Views can do a lot more than that, but those are some of the obvious uses of Views.

Here is a series of awesome tutorials on Views  (I am not affiliated with the author(s))


Converting JavaScript from Drupal 7 to Drupal 8 standards I have a Drupal 7 module that contains a JavaScript file whose only contents are

Drupal.behaviors.InitializeMapplic = {
  attach: function (context, settings) {
    jQuery("#mapplic").mapplic(Drupal.settings.mapplic);
  }
};

I'm aware that Drupal 8 introduced a new JavaScript API and that this code needs to be updated. However, I'm confused as to what the Drupal 8 equivalent is. I have read and tried to dissect the change records at https://www.drupal.org/node/1793334 and I have reviewed the API documentation at https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview.

So my question is, exactly what needs to change here in order for this to play ball with Drupal 8? Will it just become

jQuery("#mapplic").mapplic(drupalSettings.mapplic);

all by itself or what? Any light that can be shed on this for me would be appreciated.

As you already linked from the docs https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview I just repeat the most important parts here:

MYMODULE.libraries.yml

foobar:
  js:
    js/foobar.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

js/foobar.js

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $('.MYSELECTOR', context).once('myCustomBehavior').each(function () {
        // Apply the myCustomBehaviour effect to the elements only once.

        // I guess you have to pass something to `settings` first.
        // $("#mapplic").mapplic(settings.mapplic);

        console.log('Hello world!');
      });
    }
  };
})(jQuery, Drupal);

MYMODULE.module

function MYMODULE_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] =  'MYMODULE/foobar';
}

Update: removed some flaws.


How do I make translatable views? I want to have the front page view with my own title, but if I add it, it is shown for all the languages.

Is it possible to have a different title for each enabled language?

Enable the module "Configuration Translation" and then you get a tab "Translate view":

/admin/structure/views/view/[view]/translate

where you can add translations and edit the translated view.

The title is in:

Displays -> Master Display Settings -> [View] Default Display Options -> Display title


Making a view of simple text sentences My aim is to make a view of 20 sentences. The problem is all of them sit in the same Input-field and I really have no plans to open 20 different text-fields, i.e one for each sentence...

Is there Any way I could make a grid view of these 20 sentences easily from 1 input field? Thx.

One option:

create a content type (sentence) with only a title (sentence 1, sentence 2, etc) and body
create 20 pieces of sentence content, each with one of the sentences you want
create a new View, content type: sentence, page, show 20, no pager, table of fields
add the body field to the table, and remove the title

Now download the Editable Views module:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.

and set it up for that View of sentences.

create your normal View of Grid, with the body field from the sentence content type and set it up however you would normally do so

With this set up, you can easily create the grid of sentences you want, plus it will create an easy way to edit those sentences (Editable Views) so that you don't need to go to 20 different pieces of content to update the field - it can all be be done from one View page


REST API and date field format I have an angular front end with D8 backend. I am populating a content type that has a Date field. I am successfully creating the content-type with the all its fields including the Date field. The format I am sending via POST looks like 2017-07-07. It gets saved and I can even retrieve the data.

The problem is when I edit or view the node via drupal admin, the date field is empty. If I devel the node, the value I sent is set on the field. It just will not display via in drupal. What format should I be sending the date field so it will save and populate the form.

In JS, I am sending the date like so:

var start = new Date();
var params = {
  start: {value: start.getFullYear() + '-' + (start.getMonth() + 1) + '-' + start.getDate()}
};
$http.post(API + 'entity/node', params); //etc

To set a Date Field via REST in Drupal 8, you can do this:

// Build the JSON payload.
var node = {
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hello World"}],
  "field_start":[{"value":"2017-07-21T18:11:11"}]
};

// Then POST the payload to Drupal...
$http.post('https://example.com/entity/node', node);


How the handle an override of the schema of a field type To add other data to a state field, I overrode 2 functions of the StateItem class (from the state_item module)
    public static function schema(FieldStorageDefinitionInterface $field_definition) {
        $schema=StateItem::schema($field_definition);
        $schema['columns']['json']=[
            'type' => 'json',
            'pgsql_type' => 'json',
            'mysql_type' => 'json',
            'not null' => FALSE,
            'description' => "Store data about states in json format",
        ];
        return $schema;
     }
    public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
        $properties=parent::propertyDefinitions($field_definition);
        $properties['json']=DataDefinition::create('string')
        ->setLabel(t('Data'));
        return $properties;
    }

As I have already several fields of this type in my website, I got the following errors in the Status report page:
Entity/field definitions  Mismatched entity and/or field definitions
                          The following changes were detected in the entity type and field definitions.

...followed by the fields that must be updated.
Knowing the fact that I am the only user of this custom field, what is the best approach to handle this kind of change?
Here is the solution
As explained by @sanzante, I created an UpdateN function which is updating all the fields of the state type by adding an appropriate column to the table of each field:
function mymodule_update_8001() {
  $spec = [
    'type' => 'json',
    'pgsql_type' => 'json',
    'mysql_type' => 'json',
    'not null' => FALSE,
    'description' => "Store data about states in json format",
  ];
  $schema = Database::getConnection()->schema();
  $state_fields = \Drupal::service('entity_field.manager')
    ->getFieldMapByFieldType('state');
  foreach ($state_fields as $entity_type_id => $fields) {
    foreach (array_keys($fields) as $field_name) {
      $table = $entity_type_id . '__' . $field_name;
      $table_rev = $entity_type_id.'_revision' . '__' . $field_name;
      $new_field_name = $field_name . '_json';
      $schema->addField($table, $new_field_name, $spec);
      $schema->addField($table_rev, $new_field_name, $spec);
    }
  }

}

The key points are :
1-how the table names are constructed. (see $table and $table_rev in the code)
2-how the new field names are constructed. (see $new_field_name in the code an the fact that you must use the same column name as defined in $schema['columns']['json'])
3-You must use the same spec as the ones defined in function schema
After the updated ran, I still got the Mismatched entity and/or field definitions error message.
I could solve this by running drush entup (the module devel_entity_updates must be installed)

You have to write an update function that changes those fields live in your database so they match the new definition.
Time ago, this was done using the drush entity-updates command. However, this was dangerous in some circumstances. You can check the Support for automatic entity updates has been removed change record to get more information on this.
In this change record you can see:

Starting with 8.7.0, Drupal core no longer provides support for
automatic entity updates. Whenever an entity type or field storage
definition needs to be created, changed or deleted, it has to be done
with an explicit update function as provided by the Update API, and
using the API provided by the entity definition update manager.

Therefore, you need an update function. Probably, you should read the "Updating Database Schema and/or Data in Drupal 8" page, specially the "Adding a new column" section:

Here's an example of what to put into your hook_update_N() function to
add a new column to an existing database table:
  $spec = [
    'type' => 'varchar',
    'description' => "New Col",
    'length' => 20,
    'not null' => FALSE,
  ];
 $schema = Database::getConnection()->schema();
 $schema->addField('mytable1', 'newcol', $spec);

Devel Entity Updates module
As pointed out by @Ales, you may try the Devel Entity Updates module:

This command should be able to fully replace the legacy drush entup or
drush entity-updates commands.

However, this module is not meant to be used in production environments, see the following disclaimer from the module:

The goal of this module is to have a quick way to apply schema updates
while developing new entity types and ending up incrementally
adding/removing/changing entity type/field definitions.
When these changes are part of an official release (and not in the
scope of a code development session), they should absolutely rely on
DB update functions, as explained in the CR above, because that's the
only way the entity schema update process can be predictable and
reliable.

So, this approach is ok for you if don't have a production environment yet. Of course, you can ignore the warning and install the module on prod, but keep in mind that you may lose data because the operation is not safe.
You can try it on a test environment, and if you finally take the risk and use in prod make sure you have a recent backup at hand.
Why you need this
The problem you have a difference between the table data definition in code and the actual data tables in your database. Why does this happen? There are different circumstances that can lead to this. In your case, the State module has some data definitions that are applied when the module is installed. At this point, code data definition and actual data tables are matching. However, if you make any changes on the code that defines the data tables the problem arises: you have one definition on code and different actual data tables in the database.
So what you need to do is modify the tables to match the data definition. That's what my answer tries to explain. The two methods are writing an update function (so you control with that function how to modify the actual tables) or trust an automatic method (the entity update command). The command is easy but it has no brain so it just modifies the tables without thinking on possible issues. That's why you may have problems (data loss, mainly) using that command.


Accessing all VIEW data in a preprocess hook I have the following hook method:

hook_preprocess_views_view_unformatted(&$vars)

I can obtain the VIEW like so:

$view = $vars['view'];

When I dump this result I can see a complex structure with all the data I need...the VIEW can be iterated via:

foreach ($view->result as $index => $record)

Each records data (node details) is navigable via the following path:

$record->_field_data['nid']['entity']->field_XXX

I am uneasy accessing these details with the second property in this chain as usually "underscore" represents private...maybe it is just the OO purist in mean telling me it's bad practice and I am defeating OCP. :)

Ultimately I need the ability to iterate my custom fields and this seems to be the only way I can achieve that -- is there not a API which would encapsulate this access for me?

I assumed the $view object itself would have an API to provide traversing methods or at least result iteration, but it doesn't appear that way.

The result array in the Views object contains the row information so yes, if you need to access the results, this is the way to do it.

For example, including:

function YOURMODULE_preprocess_views_view(&$variables) {

  $view=$variables['view'];
  drupal_set_message('<pre>' . print_r($view->result, TRUE) . '</pre>');

}

and then a quick View that just returns node objects would look like this:

and a View that returns fields (in this case just titles) would look like this:

and then when you actually include custom fields, you get that big _field_data array, eg:

but you should also see it in a more top level area of the results as well:

Also, a quick look at views_get_view_result() might shed some more "this is how we do it" confirmation/information on Views results.  Also What is the hook to preprocess a view and Changing values in preprocess view function talk about other options available to you in the Views API.


how do i add last name new field in default user registration page how do i add last name new field in default user registration form my code is

$form['account']['lname'] = array('#type' => 'textfield',
  '#title' => t('LastName'),
  '#default_value' => $edit['LastName'],
  '#maxlength' => LASTNAME_MAX_LENGTH,
  '#description' => t('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
  '#required' => TRUE,
);

but i don't know how to show last name field in default user registration form?

I would use the content profile module, you can add new fields to a users profile just like how you use cck to add new fields to a node. There is a configuration option where you can then set which fields you want displayed on the registration form.


How do I create a total blank page without any header and footer? I am using Drupal 6 and I am stuck in a situation where I need to create a blank page without any header footer which comes as a part of your theme when you create a new page in Drupal.

I have searched lot on this problem  :

Drupal link that I used to get solution, but not helped.
Create a content type to get blank page  solution also not able to solve my problem.

Can any one help me to create blank page without any theme components.

I also read about creating a hook but I am not able to create any hooks.

How I can resolve this issue?

You can make a copy of page.tpl.php in your theme and rename it according to the Template Suggestions for Drupal 6.

Your theme should be in a directory like site/all/themes or sites/default/themes.

So if you wanted a custom page.tpl.php for http://yoursite.com/path/to/override, your file name will end up being something like page--path-to-override.tpl.php.


Drush hangs when trying to bootstrap Drupal Running Ubuntu 12.04 with the 14.04 backports for Drush (meaning we are running Drush 5.10.0)

After importing the database (with drush sqlc < dump.sql), Drupal is no longer able to be bootstrapped by Drush.

drupal-site@uat-previewweb1:/var/www/drupal/uat-preview/current$ drush st -v -d
Bootstrap to phase 0. [0.01 sec, 3.81 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 4.04 MB] [bootstrap]
Loading drushrc "/etc/drush/drushrc.php" into "system" scope. [0.01 sec, 4.04 MB]                                                                            [bootstrap]
Cache HIT cid: 5.10.0-commandfiles-0-42f7d1cb79623ad6de6c23932c9a4e2b [0.02 sec, 4.07 MB]                                                                        [debug]
Bootstrap to phase 0. [0.06 sec, 9.04 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.08 sec, 9.04 MB]                                                                                [bootstrap]
Initialized Drupal 7.31 root directory at /var/www/drupal/uat-preview/releases/20140911-4 [0.09 sec, 10.69 MB]                                          [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.09 sec, 10.7 MB]                                                                                [bootstrap]
Initialized Drupal site uat-preview at sites/default [0.09 sec, 10.7 MB]                                                                                [notice]
Cache HIT cid: 5.10.0-commandfiles-2-c32acd775c18a90c5b41d0fc9accf5ab [0.09 sec, 10.71 MB]                                                                       [debug]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.1 sec, 10.75 MB]                                                                          [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_database() [0.1 sec, 10.81 MB]                                                                               [bootstrap]
Successfully connected to the Drupal database. [0.1 sec, 10.81 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_full() [0.12 sec, 11.92 MB]                                                                                [bootstrap]

The command hangs here and does not return.

Does anyone have any ideas on what could be causing this? Is it worth it to stray from debian packages and run Drush 6.4.0 here?

In this particular case, the issue was with an incorrectly configured memcache server settings, the Drupal environment in question was attempting to communicate with a memcache instance that had a firewall dropping all connections.

The fix was to configure memcache servers in the Drupal settings file. Hope this helps someone else.