How to get visitors count of a page created using views I have created a page in Drupal using views. Is there any option to get the count of visitors that visit the page?

Enable the statistics module that comes with core in admin/module. You can start tracking pages once you enable the log settings in admin/config/system/statistics

Once you enable the Setting Enable access log drupal will start tracking all pages. Now follow below process to create a view.

Create a view with base type as access log
Enable aggregation in the other settings
Add Access Log path field and set "Group results together" in aggregation settings next to field settings.
Add one more field access log path and select Aggregation type as count.
Now you can see all paths and number of visits associated with them.
Add filter access log path and provide the path for which you would like to see number of visits.

Find the exported view below.

$view = new view();
$view->name = 'statistics';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'accesslog';
$view->human_name = 'Statistics';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Statistics Custom';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Access log: Path */
$handler->display->display_options['fields']['path']['id'] = 'path';
$handler->display->display_options['fields']['path']['table'] = 'accesslog';
$handler->display->display_options['fields']['path']['field'] = 'path';
/* Field: COUNT(Access log: Path) */
$handler->display->display_options['fields']['path_1']['id'] = 'path_1';
$handler->display->display_options['fields']['path_1']['table'] = 'accesslog';
$handler->display->display_options['fields']['path_1']['field'] = 'path';
$handler->display->display_options['fields']['path_1']['group_type'] = 'count';
$handler->display->display_options['fields']['path_1']['label'] = 'Count';
/* Filter criterion: Access log: Path */
$handler->display->display_options['filters']['path']['id'] = 'path';
$handler->display->display_options['filters']['path']['table'] = 'accesslog';
$handler->display->display_options['filters']['path']['field'] = 'path';
$handler->display->display_options['filters']['path']['value'] = 'admin/config/system/statistics';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'statistics-custom';

That's it :-)

If you would like to display page counter contextually then below code in a custom block will help.

<?php
$path = $_GET['q'];
drupal_set_message($path);
$visits = db_query("SELECT count(*) FROM {accesslog} where path = :path", array(':path' => $path))->fetchField();
echo "Views: " . $visits;
?>


Search the node using keyword I have created a text box with button to search the node which has the key word given in text box. Is there any possible to search the node in Drupal 7 with custom search button and textbox which is in tpl file

You can not include search box generated by custom search module into views, but you can add exposed filter into views to implement search functionality in the views.

To implement search functionality in the views

Add "field" in the filter and choose "Contains" from the operator list
Exposed field in the filer

It will display a search box for that field in the views and work nicely for searching. Moreover, you can enhance its display by using views tpl and control where to display this views block.


Give permissions to a non-admin user for custom rules components I have a view, format: table; and a few fields:

Bulk operations: Content
Content: Title
Content: Price
Content: Stock 1 (Stock 1)
Content: Stock 2 (Stock 2)
Content: Stock 3 (Stock 3)
Global: Math expression (Total Stock)
Global: Math expression (Total Price)

At Configure field: Bulk operations: Content section SELECTED BULK OPERATIONS i selected Delete item and another 3 options (rules components). These are: new_value_for_stock_1, new_value_for_stock_2, new_value_for_stock_3, new_value_for_price.

Admin user can see all these options (rules components), but a non-admin user (eg. an editor role) can see only Delete item.

Is there a method (trick) to give permissions for a non-admin user (role)?

I enabled Actions permissions (VBO) and in Administration » People » Permissions are displayed only default actions (eg. EXECUTE Delete item). The custom rules components aren' displayed there.

You can set permissions on rule component page in fieldset at the page bottom.

There is an option "Configure access for using this component with a permission."


Image field: mark an image as a "cover photo" with a radio button In a given content type, I have three Image fields, each of them set to Unlimited cardinality. It's like a little gallery with 3 fixed albums: when using Display Suite, I have the ability to limit the number of values getting displayed, I limited it to 1:

and this way only the first image gets displayed. The fields link to a page created by Views, which shows the images separately as a gallery, etc...

Here's an example of the result:

What I would like to achieve is to provide a radio button near the images to the user when editing these fields to be able to select which image I would like to show as a "cover photo" without reordering the images. In the example above, I can only show the 1st one in the "album".

Do you have any ideas for that? Is there a module for this task, or do I have to code?
Can I solve this problem without converting my solution to other gallery solutions? I was thinking about Flag module, but I couldn't find out how I could use it for this task. I'm using File entity (fieldable files) module, which may help in solving this question.

One approach would be to use file entity and add a field to the image file entity, but that would require re-working your current solution quite a bit.

Another approach would be to use the

Field Attach API

e.g:

field_attach_form
field_attach_submit

to attach the additional field to the image. The field would then need to be checked during output to show/hide that image as the cover image.

Update:

Here's an example to add a checkbox to an image field. I had some settings on the instance form to show/hide the extra fields, removed for conciseness here. You may be able to use hook_field_attach_form though I used a element process hook instead.

/**
 * Implements hook_element_info().
 */
function MODULE_element_info() {
  $extra = array(
    '#process' => array('MODULE_element_process'),
  );

  $elements = array();
  // Add our process function to all managed_file elements
  $elements['managed_file'] = $extra;

  return $elements;
}

/**
 * An additional preprocess callback to append the form.
 */
function MODULE_element_process($element, $form_state, $complete_form) {

  if (!isset($element['#entity_type']) || !isset($element['#field_name'])) {
    return $element;
  }

  // You can get the field data, settings etc.. like this
  $item = $element['#value'];
  $field = field_info_field($element['#field_name']);
  $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
  $settings = $instance['settings'];
  $widget_type = $instance['widget']['type'];

  // Add element, only if file id available
  if ($element['fid']['#value']) {
    // Note default value selects from cache / db table TABLE_file_data
    $element['cover'] = array(
     '#type' => 'checkbox',
     '#title' => t('Cover'),
     '#default_value' => MODULE_file_data_value($element['fid']['#value'], 'cover', '')
    );
  }

  return $element;

}

/**
 * Implements hook_field_attach_presave
 *
 * Saves a files additional field data.
 */
function MODULE_field_attach_presave($entity_type, $entity) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $supported_widgets = array('image_image', 'imagefield_crop_widget');
  $instances = field_info_instances($entity_type, $bundle);
  foreach ($instances as $field_name => $instance) {
    if (in_array($instance['widget']['type'], $supported_widgets)) {

      $settings = $instance['settings'];
      // I have some settings I check as well, if enabled on field instance..
      //if (empty($settings['display_cover'])){
      //  continue;
      //}
      // Find all of the field items.
      $items = field_get_items($entity_type, $entity, $instance['field_name']);

      if (is_array($items)) {
        // Loop over and save extended field values
        foreach ($items as $delta => $item) {
          $fields = array();
          if (!empty($item['fid'])) {
            if(isset($item['cover'])){
              $fields['cover'] = $item['cover'];
            }
            $fields['changed'] = REQUEST_TIME;
            db_merge('TABLE_file_data')
              ->key(array('fid' => $item['fid']))
              ->fields($fields)->execute();
            // Need to clear entity cache for this file
            // as update was not with api but direct query
            cache_clear_all($item['fid'], 'cache_entity_file');
          }
        }
      }
    }
  }
}


Is there a way to input the data of multiple content types all on the same page? I have three content types: student, course, and student_takes_course (student_takes_course have two reference fields that points to the student and course content types).

To input a new student_takes_course record, I would first have to go to the student content type and input a new student record, and then go to the course content type and input a new course record, and only then I can go to the student_takes_course content type and input a new record that have references to the newly inputted student and course records).

But is there a way to input the student and course and student_takes_course records all on the same page?

You can use the module Inline Entity Form as widget for student and course in your student-course content type.

This widget loads the node form for student and course in student-course content creation form, so you can fill all the data in the same place.


Is it possible to customize user profile URLs based on a custom profile field? At the moment, my user profile URLs are changed in the standard way with pathauto, e.g.:

/users/user.name

However, I have different types of users (e.g. students, faculty, staff, etc.).

I would like the URL of each user's profile page to reflect that, e.g.:

example.org/students/user.name1
example.org/faculty/user.name2

The user type is set in a custom profile field: profile_user_type.

Is it possible to customize the URLs based on a profile field (in Drupal 6)?

As Pathauto uses the tokens provided by the Token module, you could use the Token Profile module that implements tokens which return the value of user profile fields.


Dynamic Form Elements state with multiple conditions Can someone please help me figure this one out.  I have a form element that is dependent on certain values from another select.  It is only visible if certain values are selected.  I know i can do multiple conditions using different form elements.  However, how can i specify the same form element having multiple values.  Right now this only works for the last value.

$form['listing_attributes']['sort_by'] = array(
'#type' => 'select',
'#title' => t("Sort By"),
'#description' => t('How you would like the listing to be sorted by.'),
'#options' => array(
    'alphabetical' => t('Alphabetical'),
    'program_type' => t('Program Type'),
    'level' => t('Degree Level'),
    'subject' => t('Subject'),
    'category' => t('Category'),
),
'#states' => array(
  'visible' => array(
    ':input[name="listing_page"]' => array('value' => 'school_page'),
    ),
),
);

$form['listing_attributes']['group_by'] = array(
'#type' => 'select',
'#title' => t("Group By"),
'#description' => t('How you would like the sorted list to be grouped by.'),
'#options' => array(
    'program_type' => t('Program Type'),
    'level' => t('Degree Level'),
    'subject' => t('Subject'),
    'category' => t('Category'),
),
'#states' => array(
  'visible' => array(
    ':input[name="sort_by"]' => array('value' => 'level'),
    ':input[name="sort_by"]' => array('value' => 'category'),
    ':input[name="sort_by"]' => array('value' => 'subject'),
    ),
),
);

I found a way to use the "!" in order to specify what element i do not want it to show up for.  Its certainly an option and i can definitely use it.  Just thought you

'#states' => array(
  'visible' => array(
    ':input[name="sort_by"]' => array('!value' => 'alphabetical'),
    ),
),


Can Ubercart be adapted to print a letter? When an order is received through Ubercart, the details can be viewed and printed, but can the print order option be expanded to do more? When I ship product, I like to include a personalised letter in addition to the standard order form.

Can I craft such a letter, so that it prints out after the order page, showing letterhead, date, customers address, and separate envelope?

Yes. In D7 there's a 2 step process to this.

Copy ubercart/uc_order/uc_order-invoice-page.tpl.php to your current theme directory and flush your cache; this will let you create your own custom version of the the order template.
Add this snippet to your new template after <?php print $content; ?>; this will add some markup/CSS that will be rendered as a new page when treated as a printable document.

<?php /* Print only from administration page*/ ?>
<?php if(preg_match('/admin\\/store\\/orders\\/\\d+\\/invoice\\/print/', current_path()) == 1): ?>

NEW PAGE

<?php endif; ?>

If you're running a D6 site, it's a little more of pain (D6 UC ignores some theming conventions).

You'll need to copy ubercart/uc_order/templates/uc_order-customer.tpl.php to ubercart/uc_order/templates/uc_order-custom.tpl.php
Have a module define a new custom template via hook_uc_invoice_templates(): function MYMODULE_uc_invoice_templates() { return array('custom'); }
Set the new invoice in order setting page (admin/store/settings/orders/edit/basic).
Use the code in the above D7 example inside uc_order-custom.tpl.php. You'll have to modify since I don't think current_path() exists in D6. However, the same frontend logic still exists (add some extra markup in the template with CSS to generate a 2nd page).

There might be a better way to do this, but I've not touched D6 UC templating in a long time.


Unable to set drupal_set_message() after logout redirect I want to show a message via drupal_set_message() after logout and redirects to page.

Code:

/*
 * Implements hook_user_logout().
 */
function example_user_logout($account){
  $login_message = 'You have been redirected';
  drupal_set_message(t($login_message));
  $login_redirect = '/mypage';
  example_redirect($login_redirect);
}

/**
 * Redirect path for logout.
 */
function example_redirect($path) {
  $response = new RedirectResponse($path);
  $response->send();
  exit;
}

Tried commenting exit also, but still no luck.
Any help would be appreciable.

drupal_set_message() sets the message in $_SESSION. By logging out, you destroy the current session and thus wipe the message you just set.


Problem with showing custom html.twig content im making a custom menu for the homepage. My issue is that whenever I change block--system-menu-block.html.twig to something else that it suggest in the debugging like for example: block--system-menu-block--main.html.twig or block--hoofdnavigatie.html.twig it's not showing up anymore. I've cleared cache, switched themes, but nothing works. It does show up in the dubugging tool that firefox has but theres 0 content in it.. Am I doing something wrong >?

I've tried this on my site and used main navigation and it worked. block--mainnavigation.html.twig

What you can check:

Of course check if you have some typo in file name, or try with
default navigation to see if it works.
https://www.drupal.org/node/2598914 Try to disable Twig cache while you are developing.
Try to use cache rebuild with Drush https://drushcommands.com/drush-8x/cache/cache-rebuild/

I don't think that you are doing something wrong, problem is with caching I believe.


Drupal Webforms arrange fields and labels I need to create form like below

Label(Full Name)     TextField            Textfield

                 Label(First Name)    Label(Last Name)

How can I achieve this in webforms?
In webforms there is no option to show labels below.

There is a module Arrange Fields which will help you.With this modle you can Drag and drop fields into any arrangement you want.


How to apply some rules to fields in native contact form? I use the native Drupal 8 contact form with different custom fields.

I need to apply some rules more precise than the classic "required". For example, telephone number accepts only numeric characters and needs to be filled with 10 characters.

What is the best approach to do that with Drupal in a native way ? Is there a module that can do it ?

I can do it with jQuery but i would like to do it on a server side way.

If your real case is the telephone example, you need to enable the Telephone module that comes with Drupal 8 Core. Then add the telephone field to your contact form in "Manage Fields".

If you think you're doing something "popular" chances are high that someone already did it (ie Telephone module), so don't rebuild the wheel.

If your scenario is some special use case, then you want to do a custom form validation for your form field. See How do I add a custom validation to an existing form/field?


How can we display permissions to users? Is there any way we can display user permissions (e.g. delete all nodes) to a user role inside a view?

Permissions would be change-able with check-boxes.

To create a view of permissions you'd have to write a custom module that would allow views to do the search. I'm not aware of a module that does that now. Given how roles are defined and managed this would be a challenging module to get right.

If you just want to improve the user interface for permissions form you might look at these modules:

filter permissions
Permission Select
Fast Permissions Administration

If you want to give admins a limited number of roles they can assign the Role Assign module may provide what you need.


Gettting errors after install drupal-8.2.6.nl.po I add Language Dutch and import drupal-8.2.6.nl.po

This error is showed on every page: sourcetext 'The file could not be created'

What should I do?
1. Uninstall dutch language?
2. reinstall dutch language?
3. change language settings?

(copying from my comment)

Sounds like your public file system is not writable, which is necessary to generate translation files for JS. When you get an error like this, always check the status report page.


Use value from buildForm() in submitForm() My buildForm() method queries the database and returns data which is used to calculate default values for the form. How can I use these values in submitForm() without querying the database again?

Typically, the $form_state object can be used to stash that data. $form_state->getStorage() references a simple array that you can put whatever you like inside, which you can then retrieve in submitForm() the same way.


Problem with creating page for the path of page display of a view I created a library content type. Its view is library__view; this view has a page display whose path is library, which has a contextual filter on the subject of the books(e.g. math, physics).

I created a page in my theme folder, and renamed it page--library.tpl.php. I also embedded library__view using this line.

views_embed_view('library__view','page');

The problem is that library/math does not show math books (while it works right in the view administrative menu).

What is wrong with this? What is the filename of a view whose path is specified to be in a certain URL (e.g. page--library.tpl.php, library.tpl.php)?

I infer: you have created the view for listing the contents of library content type, now you are embedding that view in the page template file for theming the contents listed on the page created by view. If this is the case than you are doing the things in incorrect way.

Possible cases for creating the template file for views page:
1. Theme the contents rendered by views on http://www.yourdomain.com/library page: For this you need to create template file as per the views template suggestion, also its best to create the template for view from the suggestion generated by view at Theme: Information as below:

The suggestions for creating the template in the below image is based upon the "test-contact" page I have created in views:

2. Theming the content created for library content type: If you want to theme the contents that is rendered while creating a nodes of library type than you need to create the node--library.tpl.php. This template will be just for theming the contents of library content type created originally (not for the content listed on library page created from views) and it wont have any impact on your views page.

  Now coming to your issue of page at `library/math' does not show math books:

Check if the result in your created view displayed correctly (to confirm that the contextual filter is working fine) on passing math as argument to "Preview with contextual filters" (present at bottom of view).
Make sure that the path of page that you are creating from view is
/library, and for testing purpose you can try changing the path
temporarily to /library123 (If changing the path, than test the
result at yourdomain.com/library123/math page)
Remove the template you have created for embedding the view (as it doesn't seems to be needed, at least as of now)
Clear the cache and check again (not needed logically but no problem for testing purpose)


drush user-block feature and 'You do not have permission to block' I'm trying to use drush's user-block feature and I'm getting following error:

# drush -r . -l fqdn ublk 'user.email@host.tld.dev'
You do not have permission to block user.email@host.tld.dev.           [error]
#

I'm doing it from shell and I am root, so I'm not sure which permissions is it talking about.

Sometimes modules does not respect that user with UID 1 should be allowed to do everything. And sometimes you simply want hooks to fire with specific user's ID.

When it happens, you can use drush --user=123 where 123 is UID of an user that is allowed to perform given action.

Source: Drush issue 1126240.


Converting my project's requirements to drupal's concepts I am building a website for a client and I thought that Drupal is the best choice due to the plethora of choices that it gives me. However, this vast amount of choices made my job a lot harder. Let me describe the problem to you:

The client is selling a specific product, let's say VCRs. Every VCR is manufactured by a specific brand (e.g. Sony, LG etc). Every brand has also categories of VCRs that are similar to each other. So when we want to describe the product (the VCR) we basically have to provide the following information:

Brand (e.g. Sony)
Category (e.g. FGX ; notice that this is not unique. Another company may have the same name of category)
Model (e.g. 4523x)

I also want the users to be able to subscribe to specific brands and categories so that if Sony releases a new VCR they will be automatically notified (or if Sony releases a new VCR of a specific category).

When it came to converting all these to Drupal concepts I simply could not do it. The reason is that there are various different paths that I could use and I just don't know which one is the right one. For example:

Is the category a content type or a taxonomy term?
Is the brand a content type or a taxonomy term?
The model is obviously a content type but how do I associate it uniquely with taxonomy terms (if the answer to the questions above was "taxonomy term")?
What modules would I need to use in any case? I have checked the "Relation" module and it seems like it may contain some of the functionality that I need (along with the "rules" module, especially for the notification part).

PS: if you have any good suggestions for resources (blog posts, articles, books, videos etc) that explain how to break down every life requirements to drupal concepts I would really love if you could share them.

I would do it as follows:
Create a vocabulary called 'VCR'
Add each manufacturer as a term, then each VCR category as a child of the manufacturer. So your taxonomy structure would be like this:

LG

FGX
Other Category

Sony

FGX
Some Other Category

Note that while FGX is the same term in both places, it will have a different Term ID.

You would then add this to your content type on the Edit Fields page. Select 'Term Reference' under the 'Field' column and 'Select List' under the 'Widget' column. There are other widget options but I think select list is correct in this case.

You would then proceed to install Views, its a contrib module. It basically allows you to list content in very customised ways. (There is more to it than that when used with Panels, another module that you may need.) Go to /admin/structure/views and enable the view named 'Taxonomy term'. This will allow you to override Drupals' default taxonomy display.

At this point going to /taxonomy/term/[int] (where int is one of the taxonomy terms' id) will display all content tagged with that term. You would use Pathauto and Token to create 'pretty' URL's, I would also recommend Global Redirect whenever aliasing content.

You may need to customise the View a little, because I cant remember offhand if it will list all content, including content that is a child term of the current term by default.

Views will allow you to make blocks listing content, and you can get a little fancy and use the core Statistics module to list the most viewed product. Panels is definitely worth investigating if you have time, but in my opinion keep it used sparingly.

Views also enables you to easily provide RSS feeds that people can subscribe to. I do believe it is possible to do email updates as well but it was a while ago on Drupal 6 and my memory is shocking. I think Simple News was what we used. In as I recall it requires some configuration but you could then send an automated digest every so often. Not exactly what you requested, but it may be possible to do it with Rules as you mentioned.

If you will be doing online sales I think Drupal Commerce would be your best bet though I haven't used it in production nor played with it for about 6 months or more.

As for the PS, I couldn't find any when I started Drupal, but to me the general rule so far has been: If it isn't an object, may be useful for sorting, or categorises anything in the real world then it belongs in a vocabulary as a term.


The "Modules" page doesn't load I am running a setup on Ubuntu and WSL (Windows Subsystem for Linux) with Nginx and PHP7.4.

Drupal 8 and Drupal 9 fresh installations load every page with no problem, except the page on /admin/modules.

On the error.log file I found this error.

  2020/06/04 17:28:17 [error] 3610#3610: 1 upstream timed out (110: Connection timed out) while reading upstream, client: 127.0.0.1, server: d9.local, request: "GET /admin/modules HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.4-fpm.sock:", host: "d9.local:8080", referrer: "http://d9.local:8080/"

The Nginx configuration is the following.

server {
    server_name d9.local;
    root /var/www/d9.local/web; ## <-- Your only path $
    access_log /var/www/d9.local/logs/access.log;
    error_log /var/www/d9.local/logs/error.log;

    listen 8080;
    listen [::]:8080;

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
        allow 192.168.0.0/16;
        deny all;
    }

    location ~ \..*/.*\.php$ {
        return 403;
    }

    location ~ ^/sites/.*/private/ {
        return 403;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
        return 403;
    }

    location / {
        # try_files $uri @rewrite; # For Drupal <= 6
        try_files $uri /index.php?$query_string; # For Drupal >= 7
    }

    location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in the middle,
    # such as update.php/selection. The rule we use is strict, and only allows this pattern
    # with the update.php front controller.  This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If you do not have
    # any paths like that, then you might prefer to use a laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL pattern with front
    # controllers other than update.php in a future release.
    location ~ '\.php$|^/update.php' {
        fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
        #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
        include fastcgi_params;
        include snippets/fastcgi-php.conf;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
                fastcgi_read_timeout 60;
                fastcgi_keep_conn on;
                fastcgi_buffering off;
    }

    # Fighting with Styles? This little gem is amazing.
    # location ~ ^/sites/.*/files/imagecache/ { # For Drupal <= 6
    location ~ ^/sites/.*/files/styles/ { # For Drpal >= 7
        try_files $uri @rewrite;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }
}

Drupal 7 fresh install loads the modules page fine.

Note that page loads if you switch from Nginx to Apache. Do I cross post this to Server Fault? I just don't see it how this can be Nginx fault for not loading one specific page and people at Server Fault might not just get it or work with Drupal, I don't know what other kind of information to provide.

While the page loads, running service php-fpm7.4 restart immediately loads the complete page. I had this issue previously on all pages, which was solved reading the answer for Pages load only when you restart php-fpm, more with .gif images and previews. I am still stuck on the Modules page.

Problem was WSL1, in PowerShell with admin rights wsl -v -l

  NAME            STATE           VERSION
* Ubuntu-18.04    Running         1

Convert your WSL1 installation to WSL2 wsl --set-version Ubuntu-18.04 2

Takes about 10 minutes to finish and needs more than 10GB of free space on the drive for the process.

More at https://scotch.io/bar-talk/trying-the-new-wsl-2-its-fast-windows-subsystem-for-linux


Send order notifications when user is anonymous I find that when anonymous users are ordering something from my site I cannot send order notification messages using the "out of the box" Commerce rules.  The error message that I get says that Rules is unable to create the message entity, and the apparent reason that it cannot is that the parameter that the Commerce rule provides [commerce-order:owner] does not work [???] for anonymous users.

I can and have fixed this by changing the parameter to [site:current-user], but am wondering if there is some other way to get this to work.  [Like, for example, setting an order property?]

Since the user account for anonymous orders is created upon checkout completion, it may be that you just need to assign your custom rule a higher weight. It would need to execute after the other rule that creates and assigns the order owner user account to the newly completed order.


Faceted search show tid instead of taxonomy name I need to create a facet search using taxonomies, I have as a index the taxonomy term name but when I go to search, in the facet I see the tid and not the taxonomy term name. I follow a tutorial but I can't found the solution.

Search Index

Facet

Search

There is one issue in drupal.org talking about a TranslateTaxonomyProcessor callback processor but I don't know how to use it. Another issue talkin about the same processor: https://www.drupal.org/node/2673888

This is the list of my Processors:

You need to check "Translate entity label" option to see the name.

By editing Tag facet block you can see that option.

If you have still same issue.

You need to install Core Views Facets module.
Then select Facet source.

View Search content, display Page

Added One example o/p screenshot.


How to add auto generate password link for admin? I am using Drupal 7 for my website.
I have two roles administrator and IT.
I want to add auto generate password link at the time change the password by superadmin or IT role and also send the mail to respective user.

Please help how to add this functionality in my site.

You can used hook_user_presave() to get the changed password in your module:

function mymodule_user_presave(&$edit, $account, $category){
 echo $_REQUEST['pass']['pass1'];
}

and use the functions hook_mail() & drupal_mail() to send the email in hook_user_presave() with the changed password in $_REQUEST['pass']['pass1'].


How to conditionally send emails Drupal 8 Webform I am trying to figure out how to do the following; based on a submitted value change the email behavior:

If (field 'send' value == no) then don't send the email
If (field 'member' value == yes) then change the email message

If I can find out how to do #1 above I could use that to achieve #2, in fact I suspect they have the same answer. I am looking for a hook but perhaps that is just me being stuck in D7 style of doing things.

The latest dev release of Webform 8.x-5.x supports conditional emails and handlers.


Paypal recurring payments I'm currently using Drupal Commerce and the Commerce PayPal (https://www.drupal.org/project/commerce_paypal) module in order to allow my users to purchase items. That said, some of the items require that my customer be charged every month. Is there a way to store credit card data in order to run recurring payments (Commerce Recurring doesn't seem to be compatible with Commerce Paypal)? If I'm not mistaken, the documentation states that PayPal doesn't include the option to run recurring payments? Is there another module I can integrate in order to allow this?

We never implemented PayPal's direct recurring API, though there should be a patch in the queue to try out if you wanted. The thing to check will be real-time notifications of recurring charge failures and whether or not there's a user interface allowing the customer to cancel. Since it's PayPal, there very well may be from within PayPal itself.

PayPal does offer the ability to create Billing Agreements that you can charge against at later times, but while we included the ability to create Billing Agreements via Express Checkout, it was never fully integrated into the Commerce License Billing suite that we would normally recommend for recurring payment management.

In short, with PayPal your options are limited. If you are able to make use of Commerce Braintree instead, which is a PayPal company, I'd advise doing so, as that module offers a direct integration with Commerce Card on File (and therefore the license billing module).


How can I use webform to upload assets and create a project that can be assigned to different users I am trying to put together a creative request form that a client would fill out. A studio manager would then follow up and assign to a project manager. I am using webform and rules as a starting point with the possibility of using Open Atrium.

if you want client submissions to become content I recommend EntityForm Then you could use for example the Workbench module to assure the content is moderated by a manager into approval.

You likely want your content type to show limited items to the client and then more options to the manager. I would try to do this with the Field Permissions module.

Lastly you could automate sending emails and stuff on some events if you want using Rules.


How to populate an autocomplete using a web service? I want to populate a form field, an autocomplete widget, with values from an external REST web service without actually importing the data to my database first (on-the-fly).

How do I do that? Is there a module for that or do I need to create one myself?

There is not, as far as I can tell, a module that addresses this currently, though it wouldn't be terribly hard to build with some time on google.

But since you don't intend to harvest the responses from the API a javascript/jQuery solution may be the easiest route. Any time I build a new site I set up a module to house custom functionality in that is specific to the site, I suggest you throw together a .module and .info file and add your js that way, Drupal documentation on putting together a custom module is pretty extensive.

If this helps:

$("input#autofill").autocomplete({
        source: function (request, response) {
            var term = request.term;
            var restUrl = 'http://myRestService.com/search/'+term;

            $.getJSON(restUrl, function (data) {
                var items = [];
                $.each(data.results, function (key, val) {
                    var item = {
                        label: val.Label,
                        value: val.Value
                    };
                    items.push(item);
                });

                response(items);
            });
        }
    });


Is there any alternative way to add CCK field for Drupal 6 I am adding the amount of 2xx of fields to a content type at /admin/content/node-type/product/fields, is there any alternative way such as SQL statement to add these fields?

Thanks

Do you mean you're adding over 200 fields to a content type?! Yikes!

If so, I'd strongly recommend you look into:

Breaking the content type up into several smaller ones and using Node References to join them.
Making sure you're using multi-value fields where at all possible.
Using one or two 'Extra specification'-style free text/WYSIWYG fields to store unimportant data from many fields, provided you don't need to filter on those fields.

The issue comes down to practicality and future development... Imagine the size of your edit forms! Huge forms can actually cause problems for people's computers due to memory limitations. Imagine trying to debug or style such forms...

By breaking up the content type into groupings of fields, and collapsing discrete fields into text areas you can better normalise the data and, for a little extra work up front, save yourself a lot of pain later.

Drupal fields have entries in several tables and need many settings created, so I'd avoid using SQL to do it as it'd probably be much more work than just manually adding them.


How do I display the file size and format of attachments on a node templates? In the node template I output the attached files (multiupload file field). Need to output the size and format of each file. I do it like this:
{% for file in node.field_news_files %}Size {{ file.entity.filesize.value }} in {{ file.entity.filemime.value }} format{% endfor %}

I get this result: Size 2227507 in APPLICATION/PDF format
The goal is to get this result: Size 2MB in PDF format
Can I output the data as I need in the node template or do I need to redefine it file-link.html.twig?

There's a module which provides a Twig filter for that: Format Bytes

In twig when you get the value of a file, the size is in simple bytes and if you're intending to show it to your end-user, it's not user-friendly, this simple Twig filter helps with that and renders the file size in it's respected: 'B', 'KB', 'MB', 'GB', 'TB'

Example usage:
{{ node.field_attachment.entity.field_file.entity.filesize.value | format_bytes }}

The alternative would be to do the same formatting that module does in your own preprocess function for the template.


What is faster: hook_form_alter or hook_form_FORM_ID_alter? I want my Drupal site be as fast as it can.
So I'm considering whether to use hook_form_alter with an if statement inside or hook_form_FORM_ID_alter.
I know that it's a bit more convenient to use the latter but I'd prefer to use the faster method.

Does somebody know which is faster and how much? And I don't only mean form_alter, but all hooks with an ID in it.

The hook_form_FORM_ID_alter is faster than hook_form_alter.

Modules can implement hook_form_FORM_ID_alter() to modify a specific form, rather than implementing hook_form_alter() and checking the form ID, or using long switch statements to alter multiple forms.

Form alter hooks are called in the following order:

hook_form_alter()
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()

I hope this helps :)


drupal single page Error 324 (net::ERR_EMPTY_RESPONSE) I am having a problem I really can't figure out. I am running a drupal mobile website using mobile tools and I have also boost installed on drupal.
Now the mobile website works fine on m.domain.fr BUT ONE page doesn't work. It returns a Error 324 (net::ERR_EMPTY_RESPONSE) but all other pages ar ok.
This page is a view and I can access it just as expected in Views Editor, I have normal preview, but i can't access this page from web.

Any help would be welcomed.

Thanks

I finally found the source of the problem, it was a unsupported PHP function in the view template. As I replaced this function, the page worked normally.


How to delete all Taxonomy terms of particular vocabulary using entity_delete_multiple? I want to delete all taxonomy terms of particular vocabulary using entity_delete_multiple. For node it is working fine

$result = \Drupal::entityQuery('node')
      ->condition('type', 'page')
      ->execute();
  entity_delete_multiple('node', $result);

If i am changing taxonomy_term and type to tags or any other vocabulary, or replaced type by bundle

$result = \Drupal::entityQuery('taxonomy_term')
      ->condition('type', 'tags')
      ->execute();
  entity_delete_multiple('taxonomy_term', $result);

it is throwing error like this.

  Drupal\Core\Entity\Query\QueryException: 'type' not found in
  Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 304 of
  core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

And also i need a same query to delete user(s), watchdog and profiles.

Is there any way to do it?

Try to use vid instead of type. I haven't tried the code, but try the following

$result = \Drupal::entityQuery('taxonomy_term')
      ->condition('vid', 'tags')
      ->execute();
  entity_delete_multiple('taxonomy_term', $result);

Here is a good example for using entityQuery.

For deleting users, you can use entity_delete_multiple or user_delete_multiple

To delete user with uid 10

entity_delete_multiple('user', \Drupal::entityQuery('user')->condition('uid', '10', '=')->execute());

or pass an array of uids to user_delete_multiple

user_delete_multiple(array $uids);

I'm not aware of how to delete comments.


Does Entity Autocomplete has database leak? Lately in one of our prod database the "key_value" table became 2.4GB large.
When I took a closer look I could see that there is around 200 000 records in it, and 90% of them are entity_autocomplete collection. Then I searched the entity reference module where does it operate with the keyValue service and I found the following:

// \Drupal\Core\Entity\Element\EntityAutocomplete:129
   $selection_settings = isset($element['#selection_settings']) ? $element['#selection_settings'] : [];
    $data = serialize($selection_settings) . $element['#target_type'] . $element['#selection_handler'];
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    $key_value_storage = \Drupal::keyValue('entity_autocomplete');
    if (!$key_value_storage->has($selection_settings_key)) {
      $key_value_storage->set($selection_settings_key, $selection_settings);
    }

The $selection_settings may contain the host entity as well (it's because of the self reference feature). This means based on the code: whenever you have a new entity or the entity updated your $selection_settings_key will always be different. Also it's added to the key-value table without expiration date which will end up as a permanent out of date record (after the entity changed / field config anyhow) in your key-value table. Also because it's serializing the whole entity the record itself can be quite big (talking about 10-12 KB).

Is this a bug or am I missing something?

Known bug:
https://www.drupal.org/project/drupal/issues/2826826#comment-12376276

  As mentioned in IRC, the problem with adding even just the entity
  id/UUID to those options is that we create entity * entity reference
  key value entries.

  The key is based on the hash, so an ID/UUID in there results in a
  different hash for every entity. At the very least, we would need to
  switch to an expirable key value store, so we can clean them up but it
  is still a non-trivial overhead that is being added.

https://www.drupal.org/project/drupal/issues/2826826#comment-12644652

Seems to fix it for me:

    // Don't serialise the entity, it will be added explicitly afterwards.
if (isset($selection_settings['entity']) && ($selection_settings['entity'] instanceof EntityInterface)) {
  $element['#autocomplete_query_parameters']['host_entity_type'] = $selection_settings['entity']->getEntityTypeId();
  $element['#autocomplete_query_parameters']['host_entity_id'] = $selection_settings['entity']->id();
  unset($selection_settings['entity']);
}


Prevent a user from viewing another user's profile based on a field value I'm a Drupal veteran, but this one has me stumped . . .

I have two Profile2 profiles, one for a company and one for a job seeker. In the job seeker profile, there is an entity reference field where they add companies they don't want to view their profile. The way companies finds people is by searching via Search API. Another way, would be by browsing. I need to block both ways. Basically, the job seeker should be invisible to the companies that they've blocked.

I have Panels, Panelizer, Rules, and Views all at my disposal and know how to use them, just not in this case. Or am I better going with my own custom module?

I saw this answer Hide Profile2 fields depending on it's value when viewing user profile and that's only for specific fields, I want to block the whole profile.

This question is along the same lines of mine, but I don't see a complete answer -How to filter a view based for the current user based the value of custom fields in his profile and fields in the list of items viewed

You can control profile2 access with

hook_profile2_access

Views listens to node access so you might be able to use to exclude rows from the view.

/**
 * Implements hook_profile2_access
 */
function MY_MODULE_profile2_access($op, $profile = NULL, $account = NULL) {
  if (isset($profile)) {
    // Use wrapper for field access
    $profile_wrapper = entity_metadata_wrapper('profile2', $profile);
    // Check if $account uid is set in field_invalid_users
    if(isset($profile_wrapper->field_invalid_users)){
      if(in_array($account->uid, $profile_wrapper->field_invalid_users->raw())){
        // Deny access
        return FALSE;
      }
    }
    // Example: Explicitly deny access for a 'secret' profile type.
    if ($profile->type == 'secret' && !user_access('custom permission')) {
      return FALSE;
    }
    // In other cases do not alter access.
  }
}

One consideration is caching. Cache will need to vary enough to not serve the same cached content to valid and invalid users. Perhaps those pages aren't cached at all, it depends on your application.


Node Migrations with programmatic url aliases Can anyone advice me on how to programmatically create multiple url aliases for each row of a migration?

I am using the Migrate module to migrate page content into Drupal from an XML document.

The existing system has multiple url alias data for each page and I need that same information represented in Drupal - which is proving to be challenging.

I tried doing the following in the complete function of my custom migrate class:

function complete($entity, $row) {
    // drush_print_r($entity);
    // Create an object with our redirect parameters
    $redirect = new stdClass();
    $redirect->source = "node/{$entity->nid}";     // From URL
    $redirect->source_options = array();
    $redirect->redirect = 'http://www.google.com';        // To URL
    $redirect->redirect_options = array();
    $redirect->status_code = 0;            // Redirect Status, 0 is default
    // $redirect->type = 'redirect';
    $redirect->language = LANGUAGE_NONE;
    // Create the redirect
    redirect_save($redirect);

 /****************** **I also tried the following** *******************/
    // $entity->path['alias'] = 'test/testing';
}

I then carryout a sample migration but my url redirects are not present in the node edit area.

Can anyone help, please?

If I understand correctly, based on your example, you'll need to switch the to and from URLs. If you want the new node to display the redirects in the node edit form, the node ID should be as follows:

$redirect->redirect = 'node/' . $node->nid;

FYI - programmatic redirect creation here.


How to use Views PHP get Taxonomy field value and field collection value? I am currently using Views PHP module to use Field Global PHP to render view value,
but I dont know how to read taxonomy field value and field collection value, did anyone know how to do it??

Beside, my field collection has three field, one is boolean and the other is taxonomy fields, did anyone also know how to extract the value??

To load your field collection item and then extract the values needed, you have to load a field collection item entity as following:

entities = entity_load('field_collection_item', array($item_id))

Where your item id is the id of the field collection. This will return an array of entities, with array_shift you can get the first element out of the array. This element will contain all 3 fields.


How to redirect a user to the profile of the user they just created I have a situation where my users of role 'Operator' are in charge of creating new user accounts. Right now, when they create a new user account it just sends them back to the user/create page and displays a confirmation message.

I would like to have drupal redirect the user to the profile page (user/%) of the user that they just created.

I was looking here (http://drupal.stackexchange.com/questions/14993/how-can-i-do-a-custom-form-redirect-on-the-user-registration-form) but can't figure out how to get the user id of the user that the 'Operator' created and not the user id of the 'Operator' them self.

Here is Form API solution for that:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOUR_MODULE_form_user_register_form_alter(&$form, &$form_state) {
  // Check if user has permission to add new user
  if (user_access('administer users')) {
    $form['#submit'][] = 'YOUR_MODULE_user_register_submit';
  }
}

/**
 * Submit callback
 */
function YOUR_MODULE_user_register_submit(&$form, &$form_state) {
  if (isset($form_state['values']['uid'])) {
    // Redirect to user page
    $form_state['redirect'] = url('user/' . $form_state['values']['uid']);
  }
}

And here is Rules solution:

Add event "After saving a new user account"
Add condition "User has role(s)" — site:current-user has role "Operator". I really don't know how to check permission in Rules, so it is not the best solution.
Add action "Page redirect" — user/[account:uid]


Show oldest to newest of a date range field I am trying to figure a way to show the oldest to the newest of a date range field that is attached to a taxonomy.

For example: Tax1 (1900-1920), Tax2 (1913-1950), Tax3 (1970-1980)

So how shall I printed like this: (1900-1980)?

1) Split your taxonomy values by (-).

2) Store all the values into an array.

3) Find minimum & maximum value from that array.

Ex:

  $date = array(1900, 1920, 1913, 1950, 1970, 1980);

  $result = min($date) . ' - ' . max($date);


Can a VBO form be integrated with the Commerce Add-to-Cart form to allow adding optional add-on products with checkboxes? With VBO and Rules I can display a list of Commerce products with checkboxes and a button to add the checked products to the cart (see how).

Is there a way to integrate these checkboxes with the default Add-to-cart form from Commerce? I want to have a single Add-to-Cart form with one button, not two forms.

Alternatives I tried:

The module Commerce Product Add-on allows this, but it doesn’t use Views for the list, so I can’t customize the appearance (e.g., group the products).
The module Commerce Add to Cart Extras allows this with input fields for the quantitiy, but not with checkboxes. (The patch in Checkboxes instead of quantity doesn’t seem to work.)

Is there another way/module?

My goal is to display optional add-on products (with checkboxes) on a primary product page. If the user doesn’t select any add-on product, only the primary product is added to the cart; if the user selects add-on products, the primary product and the selected add-on products get added to the cart.

(The question Drupal Commerce - optional extra products on add to cart form seems to have the same goal, but OP seems to be fine with the Commerce Product Add-on module if it would work for him in his case. The question add to cart - multiple products at once seems to be for adding always the full set of products, so without checkboxes.)

You could do it with Custom Line Item Fields for checkboxes and either just track the add on products using the line item or create a rule that adds the matching product to the cart when an line item is added that has checkbox field values.

PS: If you go with line item fields only approach, you should use pricing rules to change the final price of any line item with those check boxes to add prices to them. If you do that, then you might want this patch that allows line item fields to automatically ajax update the price when something changes:

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


How to make multiple fields with taxonomy terms? Like so: select-taxonomy-term - price - raiting

Like this picture:

Try field_collection.  Add one to your form, allowing multiple responses for the field.  Then add term reference, price, and rating fields to the field collection.


How to remove marker from openlayers map I have Drupal 7 installation with Openlayers and Geofield (I am using Openlayers as the widget for Geofield). I am able to add new points and show them on the map, however I am not able to remove points from the map once they are edited. I guess that the answer might be pretty simple and I might be doing something wrong, however I can't figure it out!

Finally I managed to deal with it. In case someone else needs the answer:

you choose the selection tool (the one with the cross)
click on a point and press DEL


Trying to add CSS styles to a theme This is the content of the .info.yml file.

name: Endymion
description: Drupal 8 starter theme
type: theme
core: 8.x

libraries:
    - endymion/global-css

regions:
  header: Header
  primary_menu: 'Primary menu'
  breadcrumb: Breadcrumb
  content: Content
  sidebar_first: 'Sidebar first'
  footer_first: 'Footer first'

This is the content of the .libraries.yml file.

global-css:
    css:
        theme:
            css/css1.css: {}

I keep getting this error message:

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

How do I fix this error?

Additional point:

Get the same error message whether I'm running locally or on a remote server (siteground)

AFAIK you should use 2 spaces to indent your YAML. It seems you either use 4 spaces or a tab.

That is the case for the libraries files as well as the libraries key in info file.


Vague error message on config import: Config x depends on x that will not exist after import I don't understand what is missing. It's just a simple blogpost content type that I created before I reset the db and tried to re-import it. All the modules requires are enabled and I did try to clear the cache. Run updb Tried drush cim --partial. nothing has worked. This is the error:

Import the listed configuration changes? (y/n): y
Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization.                                                         [error]
Configuration field.field.node.blog_post.field_post_category depends on the field.storage.node.field_post_category configuration that will not exist after import.
Configuration field.field.node.blog_post.field_post_featured_images depends on the field.storage.node.field_post_featured_images configuration that will not exist after import.
Configuration field.field.node.blog_post.field_post_video depends on the field.storage.node.field_post_video configuration that will not exist after import. in Drupal\Core\Config\ConfigImporter->validate()
(line 737 of /var/www/localvolumes/html/core/lib/Drupal/Core/Config/ConfigImporter.php).
The import failed due for the following reasons:                                                                                [error]
Configuration field.field.node.blog_post.field_post_category depends on the field.storage.node.field_post_category configuration that will not exist after import.
Configuration field.field.node.blog_post.field_post_featured_images depends on the field.storage.node.field_post_featured_images configuration that will not exist after import.
Configuration field.field.node.blog_post.field_post_video depends on the field.storage.node.field_post_video configuration that will not exist after import.

Answering my own question, hoping it may help others. The error message above, in my case, indicates a missing configuration file.

My workflow usually involves switching between branches and re-setting the database to its pristine state. Then I try to import the configuration before finishing a piece of work.

It turns out I did not commit some field.storage.* configuration files before I switched branches and re-set the database. Then the import failed and complained about missing configuration. Re-reading the error messages more carefully allowed me to understand the underlying issue.

I used my IDE (phpstorm) local history feature to search for the missing files and restore them. This fixed the issue.


Reindex a select group of nodes I am maintaining a site that I did not build.  It was discovered that some 300 nodes of type "custom" had incorrect url aliases.  There are a total of 7961 nodes of type "custom" in the site at this moment.

$ drush sql-query "SELECT COUNT(nid) FROM node WHERE type LIKE 'custom';"

I have found the list of solr drush commands, and I see that solr-delete-index is able to remove a specific content type and then solr-mark-all could be used to indicate they should all be reindexed.  My question is, how can I reindex only the 300 bad ones on this live site.
I do have their nids in a separate csv file already, made from a custom sql query.

Just to be clear:

the site is live and important it stays that way
there is only a small portion of the content type that needs reindexed
I have all the permissions and access, no need to ask if I can get somewhere.  Assume I can.
I have the means to identify the nodes to reindex and pipe them to various things and languages.  I would even xargs a custom drush script if you have a means for doing this to a single node.

In case you don't find a better way (doesn't look like there's an existing Drush command), here's a pretty simple solution cobbled together from various functions in the module:

$solr = apachesolr_get_solr();
$nids = array(1, 2, 3, 4, ...);
foreach ($nids as $nid) {
  $solr->deleteById(apachesolr_document_id($nid));
  db_update('apachesolr_search_node')
    ->condition('nid', $nid)
    ->fields(array('changed' => REQUEST_TIME, 'status' => 1))
    ->execute();
}
apachesolr_index_set_last_updated(REQUEST_TIME);

Untested, use with caution!


Sale price not showing in cart page I have added a product in commerce. Each products have a price and sale price. In product listing page the price is cutout and sale price is displayed. When a product is added to the cart, sale price is not calculated in checkout. Instead original price is calculated. Since i'm new in drupal, I have no idea to solve this problem.

Could you change the field labels and make the field used for the price calculation the actual sale price field? The other one you could possibly call something like "original price" or so.

If this isn't feasible and you're on Drupal 8, it sounds like you want to implement a custom price resolver.


Overriding the Blog username breadcrumb in the native Blog module I want to disable the blog username in the breadcrumb which reads:
Home > Blogs > John's blog > Blog post

I have found the function in the core Blog module:

/**
 * Implements hook_view().
 */
function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => format_username($node))), 'blog/' . $node->uid)));

  }
  return $node;
}

How should I best override this function in my theme?

A node preprocess function in your template.php file would probably do the trick:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'blog' && $vars['view_mode'] == 'full') {
    $bc = function_to_get_breadcrumb();
    drupal_set_breadcrumb($bc);
  }
}

This should happen early on enough in the page build process for the changes to make their way through to page.tpl.php. You could also look at doing this in hook_node_view() in a custom module if you'd prefer.


How do I use this module which depends from a module that is not available for the core version I am using? I'm trying to install the Juicebox HTML5 Responsive Image Galleries module to the Drupal 8 site but the system doesn't allow me to do so because the Libraries API module is missing. The modules page shows the following.

Is it possible to use the Juicebox HTML5 Responsive Image Galleries module even if there is no Drupal 8 version for the Libraries API module? Could it work with the 7.x-2.3 version?

The project page for the Libraries API module shows the following message:

  This module is currently being ported to Drupal 8, but is not usable yet. Help us by following this issue.

Does it mean I can't use this API module for the Drupal 8?

Welcome to Drupal Answers.

You don't need additional module for Libraries on Drupal 8, just create libraries folder in root of a Drupal project and put all libraries you need there.

In this case download juicebox library unarchive it, put the unarchived folder in libraries folder you created and rename it to juicebox, so your library should be in /libraries/juicebox.

And that's it, you can enable your module.


How to clear or update only anonymous cache from module? I have nodes updating from my module in Drupal 7 and also complicated view with result cached in the module by cache_set() and cache_get() functions.

Anonymous users get old info with broken links and other problems after nodes updating in module. Disabling "Cache pages for anonymous users" solves the problem, but how can I update anonymous page cache by the function after update?

I can't just clear all cache because of complicated views cache, it will disable all site for the time.

cache_clear_all() is what you need.

If you need to clear cache of only one node page:

cache_clear_all('http://yoursite.com/node/' . $node->nid, 'cache_page')

(first parameter - cache id, it case of cache_page it is page url).

If you want to clear all pages cache:

cache_clear_all('*', 'cache_page', TRUE);


Getting a field value from a view I am new to Drupal8. In one of the preprocess functions in my customtheme.theme file, I need to get the value of a field from a view that I have already created. I searched the web and got:
 $view = $variables['view'];
    $view_result = $view->result;
    if (!empty($view_result)) {
      foreach ($view->result as $rid => $row) {
        foreach ($view->field as $fid => $field ) {
          $values[$rid][$fid] = $field->getValue($row);
        }
      }
    }
   $array[0] = $values[0]['nid'];

AND i got another one too :
$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

The first solution worked but I want an explanation of it please especially that I tried to print_r ($view_result) and that didn't work, so I managed to print its keys and got onyl one key which is 0. Then I got many weird keys when I did a foreach to print the keys of  $view_result[0].
I would be grateful if someone can explain to me the code and why did the getValue function take an argument ? I usually write it as getValue() only.

What you usually write as getValue() without arguments is a method of an entity FieldItemList.
$view->field returns field handler plugins configured in the FIELDS section of a View.
Views fields handler plugins are an abstraction layer for all kind of data not necessarily based on entity fields.
If based on entity fields then getValue($row) runs this code:
/core/modules/views/src/Plugin/views/field/EntityField.php:
 public function getValue(ResultRow $values, $field = NULL) {
    $entity = $this->getEntity($values);

    // Ensure the object is not NULL before attempting to translate it.
    if ($entity === NULL) {
      return NULL;
    }

    // Retrieve the translated object.
    $translated_entity = $this->getEntityFieldRenderer()->getEntityTranslation($entity, $values);

    // Some bundles might not have a specific field, in which case the entity
    // (potentially a fake one) doesn't have it either.
    /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
    $field_item_list = isset($translated_entity->{$this->definition['field_name']}) ? $translated_entity->{$this->definition['field_name']} : NULL;

    if (!isset($field_item_list)) {
      // There isn't anything we can do without a valid field.
      return NULL;
    }

    $field_item_definition = $field_item_list->getFieldDefinition();

    $values = [];
    foreach ($field_item_list as $field_item) {
      /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
      if ($field) {
        $values[] = $field_item->$field;
      }
      // Find the value using the main property of the field. If no main
      // property is provided fall back to 'value'.
      elseif ($main_property_name = $field_item->mainPropertyName()) {
        $values[] = $field_item->{$main_property_name};
      }
      else {
        $values[] = $field_item->value;
      }
    }
    if ($field_item_definition->getFieldStorageDefinition()->getCardinality() == 1) {
      return reset($values);
    }
    else {
      return $values;
    }
  }

You can see how Views API connects with Entity API, but when programming Views API code you should stay at this abstraction layer if possible.


How can I hide revision information on node forms? Trying to figure out how to hide revision information from node form. When users create a node, they see revision info at the bottom which confuses them.
I can't seem to disable revision info from the content type edit settings since there are nodes already. So the only solution is to hide it.
The way that I am going is by trying to add this:
$form['revision_information']['#access'] = false;

My question is how can I add that to my theme-name.theme file?
The content type is QUESTIONS

Please try below code in your theme-name.theme file.

/**
 * Implements hook_form_alter().
 */
function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['revision_information']['#access'] = FALSE;
}


Bypassing drupal cache in template file is there a way i can bypass the drupal cache for a specific element on my website?
in my case i've got 3 header graphics which should be displayed at a random order on every page load.

The entire page is being cached, so you'll want to disable caching on those pages that have dynamic elements. I think you'd want to:

a) turn OFF page caching for the needed paths (http://drupal.org/project/cacheexclude)
b) turn ON caching for any Views, blocks, or whatever else you can cache on those pages to save bandwidth

Then you'll have more granular caching control.


How do I grab a list of all fields in a content type? How would I grab a list of all the fields in a content type? Currently, I'm using entity_metadata_wrapper() to grab each field individually, but I feel that there's probably a more efficient way to get all of the values for a given content type.

You can use the field_info_instances to get a list of all fields for a specific entity / bundle.  In your case the entity would be 'node' and the bundle will be your content type.


Can FileTransfer be used to target remote FTP servers? I need to send files to a remote server within an ajax callback.
Snooping around Drupal's includes, I came across the FileTransfer class, but I haven't fully understood the concept of its access limit to $jail (defaults to Drupal's root).
Is it possible to use this class to access remote FTP directories as well?
If so, how?

What used for the $jail parameter is the directory for which the operations are limited; if you try deleting a file outside that directory, the operation is not allowed.

If you want FTP access to a directory on a remote site, you should use the FileTransferFTP class, and create an instance with FileTransferFTP::factory().


Pass parameters to external JS file with drupal_add_js() My organization is using Eloqua, and to this point have been using the Eloqua module. The main point of this module is just to determine where the external tracking script should be loaded on the site, and then load the external script while passing it a couple of parameters. This call is creating a huge performance hit, and so after talking to Eloqua support, I copied the external file to the site so it could be cached. Since we need the file to be loaded for every page, we really don't need the module, and so all we really need to do is load the file and pass it the required parameters

The problem is determining how to pass the required parameters to the script. Here is the current eloqua.js:

var _elqQ = _elqQ || [];

(function ($) {

  Drupal.behaviors.eloquaTracking = {
    attach: function (context, settings) {

      _elqQ.push(['elqSetSiteId', Drupal.settings.eloqua.siteId]);
      _elqQ.push(['elqTrackPageView']);

      function async_load() {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        s.src = '//img.en25.com/i/elqCfg.min.js';
        var x = document.getElementsByTagName('script')[0];
        x.parentNode.insertBefore(s, x);
      }
      if (window.addEventListener) {
        window.addEventListener('DOMContentLoaded', async_load, false);
      } else if (window.attachEvent) {
        window.attachEvent('onload', async_load);
      }
    }
  };
})(jQuery);

The _elqQ array is accessed by elqCfg.min.js, so I need to make it accessible to the script with the elqSetSiteId and elqTrackPageView parameters. Is there a way to do that while adding elqCfg.min.js via drupal_add_js() in template.php or somewhere else?

CLARIFICATION: What I'm looking for here is a way to include this file and pass the parameters to it without having to create a whole module. That seems like a lot of unnecessary overhead for this one file.

I ended up just going with a modification of the current code. I modified the behavior above so that it just loads the variables:

var _elqQ = _elqQ || [];

(function ($) {

  Drupal.behaviors.eloquaTracking = {
    attach: function (context, settings) {

      _elqQ.push(['elqSetSiteId', Drupal.settings.eloqua.siteId]);
      _elqQ.push(['elqTrackPageView']);
    }
  };
})(jQuery);

and then used drupal_add_js() to load the tracking file in my module

drupal_add_js(drupal_get_path('module', 'eloqua') . '/elqCfg.min.js');


programatically find unpublished node count in drupal I have a task to find how many node are unpublished in a particular content type. Have to use the count for some other purposes.

How can I do that?

You just want to query the node table for example

here a sample function sent the content type machine name to this function will give you unpublished node count:

function get_unpublish_node_count($type){
            $db_query = db_select('node','n')
            -> fields('n',array('nid'))
            -> condition('n.status',0,'=')
            -> condition('n.type',$type,'=')
            $result = $db_query->countQuery()->execute()->fetchField();
            return $result;
}

Same function you can use this for published node count

function get_publish_node_count($type){
            $db_query = db_select('node','n')
            -> fields('n',array('nid'))
            -> condition('n.status',1,'=')
            -> condition('n.type',$type,'=')
            $result = $db_query->countQuery()->execute()->fetchField();
            return $result;
}

just change the status to "1" will give you published node count

Hope this helps :)


Panels call custom function Is it possible to call custom code from a panel? My custom module has a function which returns some content. I wish to call this from my panel.

It is, but requires a bit of coding. You need to create a ctools content type plugin. I had the same issue a few months back, and found this to be a reasonably good guide for writing you r own content type:

http://shellmultimedia.com/articles/creating-content-type-ctools-panels-3

There are also a couple other options:

Expose the data your function is providing in a block. Blocks are automatically supported by panels.
You could (likely) use custom PHP in a panels pane. (highly discouraged)


Issue in taxonomy term with hyphen(-) in url drupal7 I have a taxonomy called free-choices.But the contents are not listed when hyphen(-) in the taxonomy name.The pages with taxonomy name without hyphen is listing contents.How to solve this issue?I checked this validation criteria .But this is not working.How to solve this issue?

How to solve this issue in the same views?

If you want a taxonomy term to be recognized wholly, then you definitely do not want to divide it with spaces, so uncheck the Transform dashes in URL to spaces in term name filter values.

Also check on the Use path alias instead of internal path option and set the correct path component. It shows set to 1, but most probably it's different component in the taxonomy path alias.

Additionally, try to use term ID instead of term name.


Get the url of image field I am using this solution to print the image for a node in the html.tpl.php file. This works, except it has the full markup. I need just the url for the image. Any ideas of how to print this out?

For instance, I am using this:

 if ($node = menu_get_object() ) {
  if ($node && isset($node->nid)) {
    $node = node_load($node->nid);
    node_build_content($node);
    $variables['field_image'] = render($node->content['field_image']);
     }
   }

If you just want the path to the original file you can use file_create_url() like this:

if ($node = menu_get_object()) {
  if ($items = field_get_items('node', $node, 'field_image')) {
    $variables['field_image_path'] = file_create_url($items[0]['uri']);
  }
}

Note that I've done away with some redundant if statements, the extra node_load (the get object call already loads the node) and the building of the node content.

If you want to use an image style insead of the original image you can use image_style_url() like this:

if ($node = menu_get_object()) {
  if ($items = field_get_items('node', $node, 'field_image')) {
    $variables['field_image_path'] = image_style_url('style_name', $items[0]['uri']);
  }
}

If you wanted to get the image style from the content type display settings you can do this using field_info_instance() like this (this example assumes a content type called "article" and a display mode of "default"):

if ($node = menu_get_object()) {
  if ($items = field_get_items('node', $node, 'field_image')) {
    // Set a default style name as fallback.
    $image_field_style = 'original';
    // Use the image style from the field settings if we have it.
    if ($image_field_instance = field_info_instance('node', 'field_image', 'article')) {
      if (isset($image_field_instance['display']['default']['settings']['image_style'])) {
        $image_field_style = $image_field_instance['display']['default']['settings']['image_style'];
      }
    }

    $variables['field_image_path'] = image_style_url($image_field_style, $items[0]['uri']);
  }
}


Custom module Pager does not work with Ajax filter My custom module uses an Ajax enabled drop down to allow users to filter images. There is also a pager attached to the query. The pager works fine when all the data is displayed i.e. no filter applied but after applying a filter, clicking a pager button just gives a white screen.

Here is my code.

function view_colouring_sheets($form, $form_state){
$query = db_select('field_data_field_image','fi')->extend('PagerDefault');
$query->join('node','n','n.nid = fi.entity_id');
$query->fields('fi');
$query->fields('n',array('title'));
$query->limit(20);
if($form_state['input']['tid']){
    $query->condition('entity_id',  colouring_sheets_filtered_tid($form_state['input']['tid']),'in');
}
$images = $query->execute()->fetchAll();

$output = array(
    '#theme'=>'image_matrix',
    '#type'=>'markup',
    '#images'=>$images,
    '#title'=>'Colouring Sheets',
    '#pager'=>theme('pager'),
    '#filter_form'=>  drupal_render(drupal_get_form('image_filter_form')),
);

return $output;
}

function colouring_sheets_filtered_tid($tid){
    $query = db_select('field_data_field_image_category','ic');
    $query->condition('field_image_category_tid',$tid);
    $query->fields('ic');
    $result = $query->execute()->fetchAll();
    $term_array = array();
    foreach($result as $row){
        $term_array[] = $row->entity_id;
    }
    return $term_array;
}

function image_filter_form($form, $form_state){
    $terms = taxonomy_get_tree(18);
    $terms_array = array();
    foreach($terms as $term){
        $terms_array[$term->tid] = $term->name;
    }
    $form['tid'] = array(
        '#type'=>'select',
        '#options'=>$terms_array,
        '#required'=>TRUE,
        '#title'=>'Fitler Images',
        '#ajax'=>array(
            'method'=>'replace',
            'wrapper'=>'image_matrix',
            'callback'=>'view_colouring_sheets',
            'progress' => array('type' => 'throbber', 'message' => 'Images Loading'),
            'effect'=>'fade',
        ),
    );
    return $form;
}

I have discovered a sort of workaround.  It requires storing the result of current_path() in a JS setting variable, and rewriting the path in JS when the pager is regenerated.

Sample code:

php
// building an ajax form...
global $base_path;
$settings = array(
    'my_module' => array(
    'my_path' => $base_path . current_path(),
  ),
);
drupal_add_js($settings, 'setting');

That will make the current page's path available in your JavaScript file to manipulate.  There are still kinks though, especially with AJAX filtering and AJAX paging all at once.  I will update this once I resolve all those kinks.


Contextual filter by taxonomy terms I have a two taxonomy vocabulary labeled as "Region and Category". Also made this as entity reference to a custom content type.

Now, I created a view of contents of "Business Page" and I want to create a contextual filter by taxonomy term, both Region and Category.

Temporarily, what I did is just focus on one taxonomy, by Region, to test if it works.

Please see images below for my configuration:

And this is the result:

My problem it is only working on term ID and not term Name.

I want to input the term Name and result would display on the page.

PS: I have a Pathauto enabled and added URL aliases to each terms.

I found this simple answer: How to use use Term:Name as a contextual filter


How can I view what causes a page to load slow? i currently have the devel module on and i'm trying to figure out why my site is slow. I get the following info line:

Page execution time was 4661.1 ms. Memory used at: devel_boot()=3.27 MB, devel_shutdown()=65.39 MB, PHP peak=70 MB.

Is there a way to view why my page is taking 4661 ms to load? Here's a view of what the page is loading:

Yes you can figure out which function(s) spends more time in the execution by using a profiling module, then you can optimize that particular function(s)

Below are the available profiling modules in Drupal 7(AFAIK),

XHProf
Profiling

Personally I used XHProf and it helped us lot to improve the performance.

  XHProf is a hierarchical profiler for PHP. It reports function-level
  call counts and inclusive and exclusive metrics such as wall (elapsed)
  time, CPU time and memory usage. A function's profile can be broken
  down by callers or callees. The raw data collection component is
  implemented in C as a PHP Zend extension called xhprof. XHProf has a
  simple HTML based user interface (written in PHP). The browser based
  UI for viewing profiler results makes it easy to view results or to
  share results with peers. A callgraph image view is also supported.

In addition to this you can also look into Performance Logging and Monitoring module which was removed from Devel.


Drupal as an interface for users to Add/Edit/Search a database I have a friend who wants to set up a site for an NPO that basically allows users to search and edit a data table with about 100 fields. My solution (being from the MS world) would be to set up a simple MVC.Net site which pretty much auto-generates pages and forms for searching and editing rows. The technology the NPO has set up however, is Drupal 7 running on Apache with a MySQL instance floating around in there.

I've searched Drupal modules and poked around with things like Data which seemed fit for constructing a UI that searches and modifies DB tables, but didn't see any way to make it work. This seems like it would be a pretty common problem people want to solve though. Can anyone propose some appropriate tools/modules for setting up such a site?

That's my question, but if you are looking for some additional information about what they're trying to accomplish, here's some relevant details:

The data we want to kick off the site with is about 300 rows in an excel spreadsheet. Something supporting a bulk data import would be preferable, but isn't required. I've already converted the data into an SQL db, so if we can simply point a module to the database, that would be great too.
Most of these are plain text fields, some are numeric, some are paragraph format (with line breaks). Rather than just text boxes for everything though, while editing and searching on certain fields, they want to present the user with a drop-down list of available values.
On the same vein as having drop-down lists for certain fields, forms that supports some customization (such as custom data validation routines) would probably be handy.
I have a grand total of about 10 hours of experience working with Drupal, but I'm comfortable with installing and configuring modules, and have ssh access to the server.

Start off with something like this:

Build Content Types for the data you want to represent. Remember that relationships in Drupal are different than the DB world and are joined with things like http://drupal.org/project/relation or http://drupal.org/project/entity_reference
Use a module like http://drupal.org/project/migrate or http://drupal.org/project/feeds to import your data and map it into your nodes. Feeds will handle what you're doing here pretty handily but if you need more advanced manipulation on the way in, Migrate is the way to go. This can basically run on some kind of cron/batch to continue a "sync" of your data.
Use http://drupal.org/project/views to build reports of your data

If you need to manipulate the data tables directly, that's not exactly what Drupal is built for. It's more than a Front End. It's a full CMF.


Boost Module problem in logged in user I have a problem in Boost module
I have a dynamic site that Allow user to logged in to edit his content

after log into the site the login links disappear and another links loaded that contain user links (I use a custom block that check if user_is_logged_in echo you content else echo sign in)

but after installing boost the menu of login still appear after registration (still read the caching page)

is there any option that  make pages to anonymous user only

This is my code

function login_block_info() {
    $blocks = array();
    $blocks['mylogin'] = array(
        'info' => t('Custom Login'),
    );
    return $blocks;
}
function login_block_view($block_name = '') {
    if ($block_name == 'mylogin')
    {
        $output ="";
        if(user_is_logged_in())
        {
            global $user;
            $query = "select nid from node where uid = " . $user->uid;
            $result =db_query($query);
            $nodes = array();
            $output ='
';
            if(count($result)>0)
            {
                foreach ($result as $node) {
                    $alias = drupal_get_path_alias('node/'.$node->nid);
                    $output .= '
'.l($node->title,'node/'.$node->nid.'/edit').'
';
                }
            }
            $output .= '
'.l(t('Change password'),'user/'.$user->uid.'/edit').'
';
            $output .= '
'.l(t('log out'),'user/logout').'
';
            $output .= "
";
        }
        else
        {
            $output .='

log in

sign up

';
            $output .= render(drupal_get_form('user_register_form'));
            $output .= '
';
        }
        return array(
            'subject' => t(''),
            'content' => $output,
        );
    }
}

thanks

Boost
  Boost provides static page caching for Drupal enabling a very
  significant performance and scalability boost for sites that receive
  mostly anonymous traffic.

I am not sure if Boost can be used for authenticated users as well. Boost will capture rendered HTML pages and store them and when a request comes for same page instead of overloading the server with PHP execution it will send the already compiled HTML pages which will greatly increase performance.
Auth cache is an alternate that allows caching for both authenticated and anonymous.


How can I create special search with check/uncheck image field in filter criteria of views How can I create special search with check/uncheck image field in filter certia of views module in drupal 8 ?

I want if users check image field checkbox and click on "go" button , they whatch only content that have image and when uncheck that they can watch all content .

You will need BEF module to get exactly what you want, but it's not ready yet.

The workaround:
Although Drupal still has a query checkbox value bug (pretty ugly:(), there is a workaround and you can come up with the following close solution:

Create a new filter criteria
Choose your image field "target_id" property.
Configuring the filtering critera check "Expose this filter to visitors"
Choose "Grouped filters"
Mark "Optional" checkbox.
Widget type: radios.
Allow multiple selections.
Mark the first grouping (Grouping 1), give it a label and choose operator "Is not empty(NOT NULL).

You are now half way through. Altough it's working like this in view preview mode, it won't on the real page (because of the bug above).

Now you need to write a hook_form_FORM_ID_alter in one of your .module file, mine's looks like this:

function base_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-page-1') {
    $request = \Drupal::requestStack()->getCurrentRequest()->query->all();
    $filter_identifier = 'field_image_target_id';
    if (!$request[$filter_identifier]) {
      $user_input = $form_state->getUserInput();
      unset($user_input[$filter_identifier]);
      $form_state->setUserInput($user_input);
    }
  }
}

WHERE:

"views_exposed_form" => form_id (you will get the same, but check it)
"views-exposed-form-search-page-1" => is the '#id' parameter of your form. (this will be probably different)
"field_image_target_id" => This is your filter identifier, which can be found (also renamed) in when clicking on views this filter criteria.


How to add JQuery code to drupal site I am trying to add my JQuery code to my drupal 7 site.

In my drupal based site i have image in the featured block.
My JQuery code slides up the image after 2 seconds.

When i added the JQuery code to my page it is showing the JQuery code on the page.

Here is my code:

<script src="/drupal/sites/default/files/js/jquery.min.js"></script><script>
$(document).ready(function(){
    $(".sec1").slideUp(7000);
});
</script>

when i save the configuration, below codes are displayed in web page.

$(document).ready(function(){
        $(".sec1").slideUp(7000);
    });

How can i solve this?

If you don't know how to add your js code to drupal, there are two ways:

Create js file in your theme_folder/js, e.g, scripts.js, put your code into that file, open .info file of theme and add scripts[]=js/scripts.js
Create a js file as I wrote above and open template.php of your theme and put

drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/scripts.js', array('type' => 'file', 'group' => JS_THEME));

in YOUR_THEME_preprocess_page().
(This is not an ideal way, but it shows how you can use a drupal_add_js() function)

also read documentation for more info.


Manage statistics with drupal I have a site that get statistics on products. I get data from an external source to update the Drupal DB to register a buy on a product and the date of that buy to be able to show a flowchart over that product.

I need this statistics for showing the development of the products selling rate. So if one customer buys a product that information will be sent to my Drupal DB, and that's where I wonder how I should construct my DB so it is optimal in speed and storage. Is it a good idea to create a content type that has a product entity reference and a date? So when a product is bought a new node is created that holds the date and product as information.

Your data should not be nodes, as they do not keep any readable content on their own, they only make sense in connection to a product and in statistics, summaries et cetera, and shouldn't really be displayed on their own. So, you have two ways of dealing with them:

Bad way - make them just a multi-value field in product content type. Not optimal for storage, not really good for filtering.
Make them entities. You only need creation date and product reference on them. Making them entities will expose them to Views for easy filtering and aggregation, to search api if you will ever need to sort by "most sold", and, well, to each and every module that knows about entities. There are many answers and tutorials out there. Hint - your entity should not be a fieldable one. Non-fieldable entities always have only fields defined at creation, so storage is much simpler for them. And simpler == faster.


How do I bypass cart and go straight to checkout? I know that you can easily achieve this functionality in Drupal 7 with the Rules module or using the Commerce Checkout Express module.

Since Rules and Commerce are not that much integrated yet, I am not sure we can achieve this that easily, in Drupal 8.

Can I implement this feature using just rules? If the answer is no, how can I do it, programmatically?

If you use the last development version of commerce, and look for file commerce\modules\cart\src\Form\AddToCartForm.php which lives under the Drupal\commerce_cart\Form namespace, you can see that cart_id was set, and it is the order ID too.

$form_state->set('cart_id', $cart->id());

Therefore, in hook_form_alter(), we can get the order ID (the cart ID).

$order_id = $form_state->get('cart_id');

The complete code would be this.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Implements hook_form_alter().
 */
function <MY_MODULE>_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // Add to cart form id for product 5 is: commerce_order_item_add_to_cart_form_commerce_product_5
    // Then it's enough to check $form_id contains the string 'commerce_order_item_add_to_cart_form_commerce'
    if(strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce') !== false) {
        $form['actions']['submit']['#submit'][] = '_redirect_to_checkout';
    }
}

// Callback for form submission
// @see hook_form_alter().
function _redirect_to_checkout(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\commerce_order\Entity\OrderInterface $cart_id */
  $cart_id = $form_state->get('cart_id');

  $url = Url::fromRoute('commerce_checkout.form',
    ['commerce_order' => $cart_id]
  );

  $form_state->setRedirectUrl($url);
}


I want to put values from additional database in drupal 7. How can I do it? I wanted to include additional values to the drupal site. Since it has around 3000 records and it is divided into categories ( a:1, a:2, a:3, b:1, b:2, c:1, c:2, c:3), I had set additional database and connected to drupal.
My question is:
How can I get those values into drupal? views? They have to be included in two forms as a checkboxes and value lists on other form to choose.

Thank you.

This thread: https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data discusses this issue quite thoroughly.


How to add Profile2 form to ctools multistep wizard I've been basing this off of Grashmash's article over building a multistep registration with Ctools, and I can't seem to get the Profile2 form in. I don't want to use the Field Group multistep option as I need to add additional forms to the wizard, but I'd like to get past this first.

I can successfully get past the initial account creation, but then the profile doesn't show up. Any ideas?

    $form_info = array(
    // Specify unique form id for this form.
    'id' => 'multistep_registration',
    //Specify the path for this form. It is important to include space for the $step argument to be passed.
    'path' => "user/register/%step",
    // Show breadcrumb trail.
    'show trail' => TRUE,
    'show back' => FALSE,
    'show return' => FALSE,
    // Callback to use when the 'next' button is clicked.
    'next callback' => 'kidb_register_subtask_next',
    // Callback to use when entire form is completed.
    'finish callback' => 'kidb_register_subtask_finish',
    // Callback to use when user clicks final submit button.
    'return callback' => 'kidb_register_subtask_finish',
    // Callback to use when user cancels wizard.
    'cancel callback' => 'kidb_register_subtask_cancel',
    // Specify the order that the child forms will appear in, as well as their page titles.
    'order' => array(
        'register' => t('Register'),
        'profile' => t('Complete Profile'),
        ),
    // Define the child forms. Be sure to use the same keys here that were user in the 'order' section of this array.
    'forms' => array(
        'register' => array(
            'form id' => 'user_register_form'
            ),
        'profile' => array(
            'form id' => 'profile2_edit_main_profile_form',
            // Be sure to load the required include file if the form callback is not defined in the .module file.
        ),
    ),
);

I found the answer in a similar thread, works perfectly with ctools.

How to display a profile form using profile2 module


Entity Reference - User reference field Hide "Restricted access" label instead of showing useless choices i have an entity reference (7.x-1.5) select-list within a checkout pane which is being used to allow the user to attach a child to a product during a checkout process.

The user can add multiple "child" under their account via field collections

The user adds a product to their cart, then checks out. During the checkout they can select a "Child" to be attached to the registrations.

My issue is when a user goes to checkout, the select list is constantly growing in values the user(from every user). The current user does not have access to these fields so the select list values simply say: -Restricted access-.

I assumed this would only show values from the logged in user, but apparently, the widget grabs ALL values from every user but hides the data the current user does not have access to. I simply need to hide all data which says -Restricted access- this data so if the user has not entered any "child" field collection data, there will be no option to select from.

Has anyone ever dealt with this issue, and what options are there to fix this? I can simply use an autocomplete widget to solve this issue, but this is poor UX in my opinion.

You change the reference widget to use Views as a filter to provide the options with Views Reference Filter. Then in Views, provide this users UID as a contextual argument to only get their own relationships instead of every user.


Drupal 6 to Drupal 7 content type migration using feature module? We have to upgrade Drupal 6 site to Drupal 7. We know that we can use migrate module for importing Drupal 6 content. But I'd like to know if we can use Features module for importing content types, taxonomies and blocks from Drupal 6 to Drupal 7?

This is already included in the core. You don't need to install Features in order to migrate all that.

Here's what you need to do in a nutshell: disable all contrib modules, make backups of everything, plug D7 into the D6 database and update the site. Drupal will take care of all basics, such as content types and fields.

Refer to the documentation for more information.