Problems with form api and #tree I'm trying to create a form element with an array of child inputs. How is the below example incorrect in D7, I'm getting this error:

Fatal error: Cannot create references to/from string offsets nor overloaded objects in C:\wamp\www\water-uk\www\includes\common.inc on line 6518

array(3) {
  '#tree' =>
  bool(true)
  '#type' =>
  string(8) "fieldset"
  'first' =>
  array(6) {
    '#type' =>
    string(6) "select"
    '#options' =>
    array(8) {
      'All' =>
      string(8) "Show all"
      [0] =>
      class stdClass#470 (1) {
        ...
      }
      [1] =>
      class stdClass#468 (1) {
        ...
      }
      [2] =>
      class stdClass#469 (1) {
        ...
      }
    }
    '#size' =>
    NULL
    '#default_value' =>
    string(3) "All"
    '#ajax' =>
    array(5) {
      'callback' =>
      string(38) "_listing_blocks_select_tax_depth_js"
      'wrapper' =>
      string(18) "tax-select-wrapper"
      'method' =>
      string(6) "append"
      'effect' =>
      string(4) "fade"
      'event' =>
      string(6) "change"
    }
    '#required' =>
    bool(false)
  }
}

You appear to be using stdClass objects for the values in your options array. Drupal expects a string for each of the options.

You probably have code like:

foreach ($something as $item) {
  // $item is a stdClass.
  $options[$item->key] = $item;
}

when you need to have something like

foreach ($something as $item) {
  // $item is a stdClass.
  $options[$item->key] = $item->name;
}


How do I change the created date when I create a node? When i do POST request for create node i get error:

{
  "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1",
  "title": "Property created cannot be set.",
  "status": 400,
  "detail": "Bad Request",
  "instance": ""
}

My restful resource provide this field:

protected function publicFields() {
  $public_fields = parent::publicFields();

  // Another fields ...

  $public_fields['created'] = [
    'property' => 'created',
  ];
}

I use restful module.

I solved this problem via hook_node_presave();

function hook_node_presave($node) {
  $node->created = "you_timestamp";
}


Exporting from Field Collections and Importing to New Content Type So here's a high-level overview of the situation: we're running into a lot of issues with the field collections module, but a lot of content has already been created for a content type that uses two fields within a field collection. We've tried to overcome some of the problems we're experiencing with field collections, and at this point it's been over a month, so we're just going to have to give up on field collection for this project.

So here's what we have. A content type like this:

Title Field
Field Collection field containing:

Subtitle Field
Body Field

And we want to export from that and create nodes in a content type that looks like this:

Title Field
Subtitle Field
Body Field

I don't really need past revisions or anything like that. I'm just looking for advice about how best to accomplish this.

Some time ago I did something similar, but with normal fields. I used Views Bulk Operations.

First I've created a view which listed all the nodes of the particular node type and added the VBO checkbox to execute arbitrary PHP code.

On the view's page I've checked all the nodes and pasted in the PHP textbox the code which updated field B values based on the field A values. In your case you should create a new node based on the field collection.

Finally, when VBO finished executing the code for all my nodes, I went to the content type fields page and deleted field A (in you case the field collection).

Done!


Building a form and printing in a block I would like to build a form, and print it in a block via hook_block().

How can I do this?

That is what done from user_block(), which contains the following code.

  case 0:
    // For usability's sake, avoid showing two login forms on one page.
    if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

      $block['subject'] = t('User login');
      $block['content'] = drupal_get_form('user_login_block');
    }
    return $block;


How to redirect logged in users accessing /user/login to specific page? This is a very specific case.

When a user is already logged in, and then tries to visit the login page, /user/login, they are redirected to their user page, /user.

This is a problem for me and I need them redirected elsewhere. To be clear, I'm not asking the much-asked question "how to redirect users after login". I'm already using r3042login and login destination.

The case explained

My site runs http and https for authenticated users. What's happening is that the user access the http site, then clicks login, logs in on https. Then the user presses Back, or a bookmark to the http site and they are not logged in (because they have a different session). So then they hit log-in, which redirects to the https site, which thinks "ah, you're already logged in!", and presents the user page. The user page is not of any interest to my users.

Ideally I'd have it such that once the https session was started, any access to the http site bounced them over to https again, until they logged out.

Ideally I'd have it such that once the https session was started, any access to the http site bounced them over to https again, until they logged out.

Maybe it can be done on web server side, but I'm not sure.

  How to redirect logged in users accessing /user/login to specific page?

Don't forget you can alter any drupal_goto() calls:

/**
 * Implements hook_drupal_goto_alter().
 */
function YOURMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  global $user;

  if (current_path() == 'user/login' && $path == 'user' && user_is_logged_in()) {
    // Redirect to front page.
    $path = '';
    drupal_set_message(t('Welcome back, %username!', array('%username' => $user->name)));
  }
}


Page slide animation with horizontal anchor navigation I want to realize a project with sliding pages (horizontally or vertically) similar to the one shown on www.viasko.de.

Is that possible with Drupal due to a different navigation concept via anchors, and not with urls? Does the URL dispatcher allow anchors?

They used here element using html like map
example

    Speisekarte

Here the point to start the page

Desc

If you don't find a module you can make it custom


Why do I get this exception when running a query? PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
  You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'default) VALUES ('1', '0', 'LSm', '054', '0')' at line 1: INSERT
  INTO {prod_conf_procuct_parameter} (prod_id, price, key1, key2,
  default) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2, :db_insert_placeholder_3,
  :db_insert_placeholder_4);  Array ( [:db_insert_placeholder_0] => 1
  [:db_insert_placeholder_1] => 0 [:db_insert_placeholder_2] => LSm
  [:db_insert_placeholder_3] => 054 [:db_insert_placeholder_4] => 0 )

function _prod_conf_db_query_insert_results_pcpp($arg,$key1,$key2,$price,$default){
watchdog('alert', "Arg: $arg, Key1: $key1, Key2: $key2, Price: $price, Default: $default");
db_insert('prod_conf_procuct_parameter')
  ->fields(array(
    'prod_id'=> $arg,
    'price'=> $price,
    'key1' => $key1,
    'key2' => $key2,
    'default' => $default
    )
  )
  ->execute();
}

watchdog() gives Arg: 1, Key1: LGm, Key2: 054, Price: 0, Default: 0.

The problem is definitively the column "default" because the insert without default|$default works.

The column is defined in hook_schema() as follows.

'default' => array(
          'description' => 'boolean indicates if the new applicated select list has default',
          'type' => 'int',
          'size'=> 'tiny',
          'default' => 0
        ),

If I run the following query from PHPMyAdmin, it works.

INSERT INTO `prod_conf_procuct_parameter`(`prod_id`, `key1`, `key2`, `price`, `default`) VALUES (1,"LSm","054",0,1)

DEFAULT is a reserved MySQL keyword. Try:

db_insert('prod_conf_procuct_parameter')
  ->fields(array(
    'prod_id'=> $arg,
    'price'=> $price,
    'key1' => $key1,
    'key2' => $key2,
    '`default`' => $default
    )
  )
  ->execute();

phpmyadmin does a lot of hand-holding and error squashing for you - it's not advisable to use it as a canonical source of truth for a particular query string's validity.


One product in multiple categories using drupal7 commerce and trying to figure out how to have a product assigned to multiple categories(old ubercart user here). The only way I have found so far is to create a new product view for each category(seems kind of cumbersome).

There is no enforcement in Drupal Commerce of any product catalog data model. The solution will depend on how you've configured your taxonomy vocabularies, really. If you have a single catalog vocabulary, simply add a multi-value taxonomy term reference field to the node type you're using to display products. This will let you assign as many categories as you want per product page.

When it comes to actually creating a View of the products, it isn't clear what you're attempting or why. A single View should be able to filter a group of nodes to any selection of or combination of taxonomy terms. You may need to export the View or paste a screenshot of your configuration to this question to get more specific help.


Loading view data using XMLRPC I need to load data from a Drupal View into an external (non-Drupal) site using PHP.

I'm using XML-RPC for PHP.

I'm able to connect to the system and login, but I'm unable to retrieve a View. I get the following error:
HTTP/1.1 401 Unauthorized: Missing required argument view_name

I haven't been able to find documentation on format of the RPC call required for views and how the session id is passed. Any pointers would be greatly appreciated. Code below. The name of the view I'm trying to get is "configurations".

require_once ("xmlrpc.inc");

// SYSTEM.CONNECT
$f = new xmlrpcmsg('system.connect');
$c = new xmlrpc_client($XMLRPC_SERVER);
$r = &$c -> send($f);

// SYSTEM.CONNECT SUCCESS
if (!$r -> faultCode()) {

    print('system connected...');
    $v = php_xmlrpc_decode($r -> value());
    $system_sessid = htmlspecialchars($v["sessid"]);

    // USER.LOGIN
    $f_login = new xmlrpcmsg('user.login', array(php_xmlrpc_encode('USERNAME'), php_xmlrpc_encode('PASSWORD')));
    $c_login = new xmlrpc_client($XMLRPC_SERVER);
    $c_login -> setDebug(1);
    $r_login = &$c_login -> send($f_login);

    // USER.LOGIN SUCCESS
    if (!$r_login -> faultCode()) {

        $v = php_xmlrpc_decode($r_login -> value());
        $sessid = htmlspecialchars($v["sessid"]);
        print('logged in...' . $sessid);

            $f_configs = new xmlrpcmsg('views.retrieve', array(php_xmlrpc_encode('configurations-xmlrpc')), array(php_xmlrpc_encode('configurations-xmlrpc')), array(php_xmlrpc_encode('configurations-xmlrpc')));

            $c_configs = new xmlrpc_client($XMLRPC_SERVER);
            $c_configs -> setDebug(1);
            $r_configs = &$c_configs -> send($f_configs);

            if (!$r_configs -> faultCode()) {
                print('got configs');
            } else {
                print('error getting configs...');
            }

        } else {
            print('error logging in...');
        }
} else {
    print('error connecting to system');
}

I think you forgot to send the the view_name that is a non-optinal argument. Check the code of the resource:

'view_name' => array(
  'name' => 'view_name',
  'type' => 'string',
  'description' => 'The name of the view to get.',
  'source' => array('path' => '0'),
  'optional' => FALSE,
),


How can i send a mail to specific user when workflow state is changed or changed to particular state? I want to send a mail when workflow state will change from creation to pending,from pending to approval and from approval to published. How can i achieve this. I have tried with rules but it can't be done using same.
I am using drupal 7.34 .

This can be achieved with the help of Rules module.

  The Rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.
  Example use cases

  Build flexible content publishing workflows changes
      Send customized mails to notify your users about important
      Create custom redirections, system messages, breadcrumbs, ...
      Build an eCommerce store using Drupal Commerce

  And many more...

Check Tutorial: editorial workflow with rules, which has good documentation on the how to's.


Local drush stops working after changing files and folder permissions So I changed the files and folder permissions with the following commands on Drupal 8 and after that, I can't run drush commands unless I change file permissions to 777

find . -type f -print0 | xargs -0 chmod 0644
find . -type d -print0 | xargs -0 chmod 0755

Here's the error I get after I run drush cr for example:

PHP Warning:  pcntl_exec(): Error has occurred: (errno 13) Permission denied in /usr/local/bin/drush-8/vendor/drush/drush/includes/startup.inc on line 415
Error has occurred executing the Drush script found at /data/websites/virtualmax.ca/public_html/vendor/drush/drush/drush
(errno 13) Permission denied

I wonder if there's a certain permission required to be able to run local drush installed with composer

Apparently, you have two Drush instances installed, as you can see in your error log, it tries to run the global Drush which is located at /usr/local/bin/drush-8/vendor/drush/drush first

the reason that you cannot run Drush commands locally after file permission changes is that it's not executable, try this in your installation root:

sudo chmod +x vendor/drush/drush/drush


Two Columns with Display Suite? I want to override the default three-column layout used by the Display Suite module, and I want to use only the left and right columns, without the middle one.
What is the easier way to achieve this?

The easiest way would be to override the nd_regions.css file in your theme and put something like the following in it:

.nd-region-header,
.nd-region-footer {
  clear: both;
}
.nd-region-left {
  width: 50%;
  float: left;
}
.nd-region-right {
  width: 50%;
  float: right;
}
.nd-region-middle-wrapper {
  display: none;
}

Simply don't put anything in the DS middle column, manage a gutter and you'll be fine.


How to let user decide how comments be sorted The scenario is, in a project comments has a vote up/down field so users can rate a comment. What I'm looking for now is a solution so user can decide if comments should be sorted by date created (newest first) or by its rate (top rated first).
Should I use a views for that? if so how can I hide main comment section?

It seems that the most obvious way to manage your user's behavior on comments would be to use Views.

And if you want to hide the main comment section, you can do so in your content type's parameters (check the comment section of you content type). You'll see stuff like hide and close.

Hope that gives you a start point.


Content type title field not available in manage display I have two customized content types, both having a title field. Yet this field does not appear in the Manage Display panel. Moreover, they are not displayed when the content is displayed.

Is this normal? How can I access those title fields? How can I have them displayed?

It is not normal
but may be the theme you use does not display page title or you hide it with css
anyway you can go to node.tpl and write echo $node->title to check that


REST API doesn't seem to work Login with CURL:

curl --header "Content-Type: application/json" \
--request POST \
--data '{"name":"admin", "pass":"admin"}'
http://d8.local/drupal-8.5.6/user/login?_format=json

Then the result:

{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"LUa3_xAXC8CgDkCoDoKonAmJ8hYFF6gZTak_LpaHFco","logout_token":"90jJUh08H437-F5fU25eq7rS2b8FS22eVVy_Fcsk2TA"}

Look good. But when I tried to check login status:

curl --header "Content-Type: application/json" \
--header "X-CSRF-Token: LUa3_xAXC8CgDkCoDoKonAmJ8hYFF6gZTak_LpaHFco" \
--request GET \
http://d8.local/drupal-8.5.6/user/login_status?_format=json

The results is: 0. So it failed.

Same result when I did with Vue resource.

Note: Postman seems to work, but it's working like real browser without CSRF token need.

Any idea?

Thank you.

REST API doesn't work with CURL because you don't send cookie after login. By default, Drupal 8 using HTTP Basic Authentication after the login user has a cookie. Browser (include postman) will store this cookie and send to the server any request. So It works normally.

If you want REST API working with CURL. You need to store cookie when request login, and send this cookie to check status login like this:

curl -c ~/cookie.txt
--header "Content-Type: application/json" \
--request POST \
--data '{"name":"admin", "pass":"admin"}'\
https://dfs3w.ply.st/user/login?_format=json

in line

-c ~/cookie.txt

mean that write cookie to file cookie.txt.

After login successfully, I will read cookie and send cookie to check status login:

curl -b ~/cookie.txt
--header "Content-Type: application/json" \
--header "X-CSRF-Token: -LSxwKsxEnupbeM4NANfV1JLtlGeqK0dRPxhRRSFvkU"\
--request GET \
https://dfs3w.ply.st/user/login_status?_format=json


How do I add a favicon to my custom theme? This seems like a simple question, but I couldn't find a clear answer when I googled so going to create one.

You can add a favicon by just adding a favicon.ico (or .png or .gif or other valid  favicon file type) to the root of your custom theme folder.

If you'd like to have your favicon stored in a custom location, see the method described here: (Change default favicon programmatically)

Edit:

If you simply want to give your theme the ability to change the favicon, without providing one yourself, you can add the setting to your theme settings folder by adding a /config/install/THEMENAME.settings.yml file to your theme, with the following settings:

features:
  favicon: true
favicon:
  use_default: false


How to sort a view using values not stored in the database I'm using a view where elements are sorted by price values,
under certain conditions the price values are rewritten on the display (if there are offers) but not in the database. The problem is that I need the results to be ordered by the rewritten price.
I can reorder the results returned by the query using a views_pre_render hook:

https://stackoverflow.com/questions/2471361/how-to-sort-view-results-programmatically

but it only affects the current page so elements are not properly ordered within the elements not shown in the current page.

Other option would be to order the view altering the query itself but since the right price values don't actually exist in the database I don't know how this could be done.
Is there a way to order the results of a the whole view when paginator exists?

I've thought about not using pagination and requesting all the elements of the view so I can create my own paginator once I've ordered the results but I'm not sure how would it affect the speed of the page.

I used a view pre render hook to alter the order of the returned rows (I had to disable pagination and create my own pagination system). Here's an example of the function:

function your_theme_or_module_views_pre_render(&$view) {
  if ('your_view' == $view->name && 'your_display' == $view->current_display ) {
    if(isset($_GET['sort_order'])){
      if($_GET['sort_order'] == 'ASC'){
        $sortorder = SORT_ASC;
      }else{
        $sortorder = SORT_DESC;
      }
      if($_GET['sort_by'] == 'field_price_value'){
        $byprice = true;
      }else{
        $byprice = false;
      }
    }else{
      $byprice = true;
      $sortorder = SORT_ASC;
    }
    $order = array();
    foreach ($view->result as $key => $row){
    /* Here you can modify the values you want to show
    and put them in an order array */
      $row->field_field_price[0]['rendered']['#markup'] = $thenewprice[$index]."€";
      $row->field_field_price[0]['raw']['value'] = $thenewprice[$index];
      $order[$key] = $thenewprice[$index]; // we will use this array for multisorting
    }

    //this will be used for pagination In my case I'll show 8 results per page
    $numpages = ceil(count($view->result)/8);
    if($byprice){
      /* we only change the rows order if we are sorting by the
      modified field, otherwise the order returned by the view is fine */
      array_multisort($order, $sortorder, $view->result);
    }

Now we create the pagination system you can use this as an example

    if(!isset($_GET['page'])){
      $view->result = array_slice($view->result, 0, 8);
    }else{
      $sumando = ((int)$_GET['page']*8);
      $view->result = array_slice($view->result, $sumando, 8);
    }
    $links = array();
    if(isset($_GET['page'])){
      $page = $_GET['page'];
      $absolute_url = full_url( $_SERVER );
      for($i=0;$i<$numpages;$i++){
        if($page == $i){
          $active = " active";
        }else{
          $active = "";
        }
        $urlconpage = str_replace("page=".$page,"page=".$i,$absolute_url);
        $links[] = "".$i."";
      }
    }else{
      $absolute_url = full_url( $_SERVER );
      $countarray = explode("?",$absolute_url);
      if(count($countarray)>1){
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."&page=".$i;
          $links[] = "".$i."";
        }
      }else{
        for($i=0;$i<$numpages;$i++){
          if(0 == $i){
            $active = " active";
          }else{
            $active = "";
          }
          $urlconpage = $absolute_url."?page=".$i;
          $links[] = "".$i."";
        }
      }
    }
    $_SESSION['links'] = $links;
  }

Most of the code in the paginator is just to keep unchanged the parameters in the url, essentials for the view returning the right results. The function full_url that I call in the code is an adaptation of the function described in:

https://stackoverflow.com/questions/6768793/get-the-full-url-in-php

Using the SESSION variable You can print the links where you prefere, For example in a global textarea in the view footer, inside an

 structure.


Filter view by passing a date via URL I have created a view and I want to show filtered posts passing arguments via the URL. Example:

http://mysite.com/press/2012-01

I want to show all press posts created in January'2012.

How can I do that ?

Take a look at the core Views example Archive (admin/structure/views/view/archive/edit) which is disabled by default.


Avoid duplicate ID for a field that appears multiple times on the same form I'm having a problem with duplicate ID's for a custom field widget.

The scenario:
I have an order form, that contains 2 field collections "pick-up" & "delivery".
Both these collections contain the same field "field_delivery_profile" which is a customer profile reference field with a custom field widget.
In the hook_field_widget_form regardless of whether I assign the element an id or not, the ID is the same for both occurrences of the field in the form.

One thing is the breaking W3C standard but the most crucial one for me right now, is that I need to check both fields value change through JS and have to be able at least predict the IDs. Is there maybe a way to get the parent field-collection (that's containing the field) information for assigning a better id?

Best,

Alari

Drupal has a helper function for that:

drupal_html_id():

  Prepares a string for use as a valid HTML ID and guarantees uniqueness.


Is translation an option in Drupal 8's logger? Drupal 7's watchdog() function has a transaltable $message and a $variables argument.

The logger in Drupal 8 doesn't seem to have option. Is it recommended to pass the output of t() to logger?

No, don't use t() for logger messages. The messages are going to be translated already and you don't want to translate twice.

Example for the cron message:

    $logger->notice('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
      '@module' => $module,
      '@module_previous' => $module_previous,
      '@time' => Timer::read('cron_' . $module_previous) . 'ms',
    ]);

This is the same as in a t() function. The difference is that the messages are stored untranslated and will only be translated on runtime so that the message can be displayed in each user's language.


Path to views in menu link I have a view that shows all the articles then I can select the year. I made this with a group filter.
At this point drupal send the user to an url /noticias?created=2

and here news of 2014 are displayed

and so on..
noticias?created=3 ---> 2013
noticias?created=4 ---> 2012
...

Now I want add a link in the main menu

News 2014 (path: noticias?created=2)

but it says: The path 'noticias' is either invalid or you do not have access to it.

The question is

How can I create a menu link for each year? I would not like to use absolute path...

Thanks

You could use contextual filters with the year as parameter. Your views path could be "noticias/%". "%" is a placeholder for your contextual filter. So you have to add 2 filter i think. Global: Null and your year date as second parameter. This method is more SEO friendly.


Change author field's empty behaviour In the form to create a node, when the author field is not filled, the author is set to the anonymous user. I'd like to hide the author field when it is not empty.

Is there a Drupal workaround for that? I am really thinking into resolving this with JavaScript which I consider a desperate approach.

Unfortunately you've no way to find everywhere this info will appears, as it will depends of the modules/templates that you're using.

So you need to identify where it is displayed, and check if user id is equal to 0 ( 0 = Anonymous user).

You can do this in hook_preprocess for example, or just add a condition in your template.
Like for example the default node.tpl.php is like this:

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

You could add this condition to hide the infos for anonymous user:

<?php if ($display_submitted && $uid != 0): ?>

    <?php print $submitted; ?>

<?php endif; ?>


identify author of an entity Using Drupal 8 and hooks, I am able to send an email to the current user, thanks to How to send mail programmatically in Drupal 8
and
BCC For drupal mail function.
So, I define my message in hook_entity_update() and send it in hook_mail().
I am trying to send emails in the following case.

user U1 consult a node created by user U2 (the aim is to permit to U1 to give his impression to U2 thanks to a select field). When U1 gave his impression, content is registered.
I need to send a email to U2 (the node author), but since he isn't the current user, I cannot use \Drupal::currentUser().

In hook_entity_update(), how can I identify the author of the current entity, knowing that "author" is not provided by Drupal\Core\Entity\EntityInterface?
Is there a specific service?

Afaik, there's no requirement that a Content Entity must store the id of the user who created/edited it. However, many entity types do use a common method to store the owner information - Drupal core's user module provides an EntityOwnerTrait that many entity types use. (At least Node, Media, etc, all use this trait.)
For example, if you're looking for the owner of an entity that uses this trait, you can use the getOwner() method like:
$owner_user_object = $entity->getOwner();

It's unclear if user U2, in your example, would be the owner of the entity or just the author of a particular revision. If your entity is storing revision information, and the entity extends EditorialContentEntityBase (Note that they probably do. Node, Media, etc, all extend this base class) then it's also possible to load the author of a particular revision.
First, load the revision. See @baikho's comment pointing to Preferred way of loading a specific entity revision.
$entity_revision = \Drupal::entityTypeManager()
  ->getStorage('MY_ENTITY_EYPE')
  ->loadRevision($MY_REVISION_ID);

Once you'd loaded the revision, you can get the author of that revision with the getRevisionUser() method like:
$revision_user_object = $entity_revision->getRevisionUser()


How to do Domain site name translation (DA module) I just want to translate site name to different language - so when users browse a domain in english they see English site name, and when they browse in polish for example, they see Polska nazwa strony.

I got all modules (Domain Access, i18n, Variable) and I had enabled two languages, checked variable (site name) in admin/config/regional/i18n/variable - but I can't translate the site name.

I try to translate it on admin/config/system/site-information page - different name for en patch and different for pl - no results, and on admin/structure/domain/view/X/config - also without any results.

Any idea how to menage to translate site name? Am I doing something wrong?

I have tried the Domain Variable module also already (as suggested in one of the answers), with no avail. I have read this nice article by Jose, but it just doesn't work on my site (Drupal 7.38, Domain Access 3.11 and latest version of the Variable module). I did set everything step by step, but I can't figure out what is going on and why this doesn't work.

The project page of the "Domain Access" module says:

  If you use the contributed i18n module suite, you should use the Domain Variable module instead of the provided Domain Configuration and Domain Settings modules.

Therefore, I think you should try the Domain Variable module, to check if it fixes you issue.


Repair Table After Server Upgrade Hello i hope someone can help me with this on here as i posted on drupal.org and folks told me it wasnt a drupal issue. I dont mind learning stuff but ive got so much drupal things that i do know about to get on with to get my site open that i dont want to spend a week trying to learn more about databases. All help appreciated. thanks.

My hosting company upgraded their servers the other now. Now my statistics module is all messed up and it's asking me to repair a table. The error message is-

  User warning: Table './onlineba_d939/node_counter' is marked
  as crashed and should be repaired query: SELECT totalcount, daycount,
  timestamp FROM node_counter WHERE nid = 4389 in _db_query() (line 148
  of /home/onlineba/public_html/includes/database.mysql.inc).

and

  User warning: Table './onlineba_d939/node_counter' is marked
  as crashed and should be repaired query: SELECT node.nid AS nid,
  node.title AS node_title, node_counter.totalcount AS
  node_counter_totalcount FROM node node LEFT JOIN og_ancestry
  og_ancestry ON node.nid = og_ancestry.nid LEFT JOIN node
  node_og_ancestry ON og_ancestry.group_nid = node_og_ancestry.nid LEFT
  JOIN og_uid og_uid ON node.nid = og_uid.nid LEFT JOIN node_counter
  node_counter ON node.nid = node_counter.nid WHERE (node.status = 1)
  AND (og_uid.uid = 1) ORDER BY node_counter_totalcount DESC LIMIT 0, 10
  in _db_query() (line 148 of
  /home/onlineba/public_html/includes/database.mysql.inc).

I have access to PHPmyadmin and i have a very very basic understanding of it. Is there a line of code or query i need to put in it to repair? I should go look maybe there is just a repair button. I think i saw that before. Anyone offer me any help before i destroy everything?

thanks

Since you have PHPMyAdmin, you should be able to fix this with some point and clicking.

Navigate to the node_counter in your Drupal database
Go to the 'Operations' tab
Hit check tables
If something isn't right it should give you the option to repair

If the option to repair doesn't come up and it doesn't appear in the Operations tab (some of these move around version to version of PHPMyAdmin), you can run the command

REPAIR TABLE node_counter;

from the SQL tab.

Good luck!


How to send multiple emails after creating a node I'm using SMTP module to send e-mail messages after creating nodes. It takes about 3-4 seconds to send each such message using hook_node_insert. So if I want to send 10 messages, then I have to wait for 30-40 seconds for the iteration to complete and then only I get redirected to create new node. It's very slow.

I tried use event KernelEvents::TERMINATE per this article, but it did not speed up the whole process.

Is there a way just to complete creating a node without waiting and immediately proceed to creating a new node, while sending e-mail messages at the same time?

Note: I don't want to create queue and wait for the next cron run to send e-mails. Because e-mails need to be sent instantly after creating respective node

As noted on the Reddit thread, this event will not work as described in this blog unless you are using PHP FPM. For most hosting providers this is the default setup. So, if you are using Apache with mod_php you are out of luck, it seems.

Are you hosting with Apache and mod_php? You'll need Apache and use PHP FPM with some settings changed. Or use nginx.

Sounds like the problem is due to your server not streaming the output. Per the Symfony docs

  Internally, the HttpKernel makes use of the fastcgi_finish_request PHP function. This means that at the moment, only the PHP FPM server API is able to send a response to the client while the server's PHP process still performs some tasks. With all other server APIs, listeners to kernel.terminate are still executed, but the response is not sent to the client until they are all completed.

https://symfony.com/doc/current/components/http_kernel.html#the-kernel-terminate-event


Click button to change CSS in D7 I'm trying to create a clickable link that changes the css using jquery. I've tried many approaches and nothing seems to work. Hopefully someone here can push me into the right direction.

Button html (in a block):

Change CSS

Button code (in change_css.js):

(function($) {
    Drupal.behaviors.my_node_toggle = {
        attach: function(context, settings) {
            $("#change_css", context).click(function(){
                $('a').css({"color":"#ff0"});
            });
        }
    };
})(jQuery);

The script is being loaded, but nothing happens when I click on the link.

Your problem resides in the way you are calling the css function in jQuery. Try this, it works for me:

(function($) {
  Drupal.behaviors.my_node_toggle = {
    attach: function(context, settings) {
      $("#change_css", context).click(function() {
        $('a').css("color","#ff0");
      });
    }
  };
})(jQuery);


How can I add a span tag inside my menu link? My twig file contains the following:

   {{ link(item.title, item.url) }}

Which outputs:

    Search

But I really want to add a  tag around the text Search (for styling purposes and replacing the text with an icon image.

I tried replacing {{ link(item.title, item.url) }} with {{item.title}} but that loses valuable attributes provided by the link function (as well as the menu_link_attributes module). I'm not sure if I can do this in twig or I need to write some sort of function in my .theme file. Any help appreciated. Thank you.

You can try this code:

{% set tmp = '<span>'~item.title~'</span>' %}
{% set link_text %}{{ tmp|raw }}{% endset %}
{{ link(link_text, item.url) }}


Creating checklist form programatically I need to create checklist form(s) comprising of a different sets of checks with different ways to enter an answer. The end user (who will prepare checklist) should not need to add fields to the structure or do any other background tasks.

I created new content type called "checklist" with some fields:

ChecklistText
AnswerOptions
Comments

For example
Item A:

ChecklistText : "Fuel Consumption"
AnswerOptions : "Liters|Int"
Comments : "Yes"

Item B:

ChecklistText : "Engine checked"
AnswerOptions : "YesNo|Logical,Name|Text"
Comments : "No"

From that data I would need to render a form. Starting with Item A it should display ChecklistText , entry field Liters and entry field comments. Form should then continue with item B and display ChecklistText , checkbox with field to enter name of the person who checked it (or none if it wasn't checked) and no comment field. At the end a submit button.

My idea how to proceed from here on would be : write a custom module to create a form from content. Parse the field AnswerOption to put correct elements on the form , name elements with an ID (from content record) prefix as to not get duplicates and then somehow submit all that. Is this possible at all with existing drupal functions ?

Was searching for similar examples , but the absence of them got me thinking that my approach to this task is totally off the mark ?

Using D7. Very new to Drupal & PHP , but coding since the age of dinosaurs. Hence my approach as a database desktop programmer.

The short answer to all this is :

Create custom module , use provided Form API
Don't parse anything, use Field Collection to add linked nodes


Pager Gone when I edit query in "views_pre_execute" Today I faced a strange problem.

Indeed I tried to manipulate SQL QUERY of a view in "views_pre_execute" event.

I made a module with name "modify_view_query" and created related function in my module.

function modify_view_query_views_pre_execute(&$view) {
}

the view name is "view_products" so I added this condition to the function.

function modify_view_query_views_pre_execute(&$view) {
    if($view->name=="view_products") {

    }
}

Then I retrieved the SQL query and tried to inject.

function modify_view_query_views_pre_execute(&$view) {
    if($view->name=="view_products") {
        $sqlStr = $view->build_info['query'];
    }
}

The original Query is

SELECT DISTINCT(node.nid) AS nid, node.type AS node_type, node.vid AS node_vid,
    node.title AS node_title, node.language AS node_language,
    node_data_field_product_brand.field_product_brand_value
        AS node_data_field_product_brand_field_product_brand_value,
    node_data_field_product_brand.field_product_dosage_value
        AS node_data_field_product_brand_field_product_dosage_value,
    node_data_field_product_brand.field_product_package_value
        AS node_data_field_product_brand_field_product_package_value,
    node_data_field_product_brand.field_product_drug_category_value
        AS node_data_field_product_brand_field_product_drug_category_value,
    node_data_field_product_brand.field_product_indication_value
        AS node_data_field_product_brand_field_product_indication_value,
    node_data_field_product_brand.field_product_type_value
        AS node_data_field_product_brand_field_product_type_value,
    node_data_field_product_brand.field_product_patient_advisor_nid
        AS node_data_field_product_brand_field_product_patient_advisor_nid

    FROM {node} node LEFT JOIN {content_type_product} node_data_field_product_brand
    ON node.vid = node_data_field_product_brand.vid

    WHERE
        (node.status = 1)
        AND (node.type in ('%s'))
        AND (node.language in ('%s'))
        AND (SUBSTR(node.title, 1, 1) = '%s')
        GROUP BY nid ORDER BY node_title ASC

I want to inject an OR condition to my code.
indeed I want to replace SUBSTR(node.title, 1, 1) = '%s' with SUBSTR(node.title, 1, 1) = '%s' OR SUBSTR(node.title, 1, 1) = '%s'

So I used string replacement function as follow.

$sqlStr = str_replace("SUBSTR(node.title, 1, 1) = '%s'","SUBSTR(node.title, 1, 1) = '%s' OR SUBSTR(node.title, 1, 1) = '%s'",$sqlStr);

Finally I set the parameter and new SQL string for the view.

    $view->build_info['query_args'][2] = 'A';
    $view->build_info['query_args'][3] = 'B';
    $view->build_info['query'] = $sqlStr;

The Final Function is

function modify_view_query_views_pre_execute(&$view) {
   if($view->name=="view_products") {
    $sqlStr = $view->build_info['query'];
    if($view->build_info['query_args'][2] == "A" || $view->build_info['query_args'][2] == "B")
    {
        $sqlStr = str_replace("SUBSTR(node.title, 1, 1) = '%s'","SUBSTR(node.title, 1, 1) = '%s' OR SUBSTR(node.title, 1, 1) = '%s'",$sqlStr);
        $view->build_info['query_args'][2] = 'A';
        $view->build_info['query_args'][3] = 'B';
        $view->build_info['query'] = $sqlStr;
    }
   }
}

every thing works fine. But the problem is when I use this code to manipulate the query the PAGER is disappeared.
I am sure that this code causes the problem because when I disable the module or comment the function Pager appears but again when I active the module or un-comment the codes Pager disappears !!!

Please help me. What is my mistake ??

I found the solution of the problem.

Indeed I manipulate the code in wrong function.

I switched to hook_views_query_alter and modify my codes in that function.

now everything works fine with no problem.

my function is

function modify_view_query_views_query_alter(&$view, &$query){ }

and I modify the query parts by changing the array values.

$query->where[0]["clauses"] and $query->where[0]["args"]


Notify site users based on user account field (e.g. apt number) I run a site for my condo, the HOA wants to setup a way to notify residents when they get a package, that needs to get picked up from the office.

In the users account settings their are both unit number and email fields.

How would you solve this problem?


Is caching certain parts of a page possible? I have created a drupal 7 commerce site that displays some real time data to visitors as current number of purchases, upcoming products in the next day or so etc. Is there a way to cache parts of the site / page so that not everything is reconstructed on every request?
For example for each product everything can be cached except from the number of current purchases, so I would like to cache images, prices, theme etc, but not the number of current purchases.
Is it possible?

If you use the Page manager together with Panels, then yes, this is trivial. Each "Pane", in a Panel can have it's own cache settings, and they can also be set on a per user basis, meaning you can cache things, even if they include data that is unique for the logged in user.

If you also add Cache actions on top of that, you can add some really aggressive caching that will be cleared only, and exactly, when the relevant data updates.


Need help with Views and Glossary Note: as a neophyte user, I'm not allowed multiple links or images. It has been suggested that I edit my original content in order to add updates. Also it's been suggested to edit the hyperlinks so they're not quite right. Hopefully you can sort out what's going on.

I've been following this post by Kristin Brinner "Drupal Tutorial: Use Views to Create an Alphabetical List of Taxonomy Terms" (at h ttp://getlevelten.com/blog/kristin-brinner/drupal-tutorial-use-views-create-alphabetical-list-taxonomy-terms) but my sample does not produce the results illustrated and by now I'm very confused.

Part 1: said to create new view showing taxonomy terms, display in grid format and create menu link. Done.

Part 2: grouped terms alphabetically (add Taxonomy term: Name, label it "Grouping", exclude from display, rewrite to max length = 1 and uncheck 'trim on word boundary' and 'add ellipsis'). Under Grid-Settings use "Grouping" apply to all displays. My view looks like the sample. Done.

Part 3, Create a Views page for each letter of the alphabet: said to add a Contextual Filter: Taxonomy term: Name. When the filter value is NOT in the url, display all results for specified field. Under More, click Glossary mode, character limit = 1. Note that I now have a Taxonomy term: Name in the Contextual Filter section. I don't know how to test these results.

Part 4, Create A-Z list (create a block that will display the list of first letters in a cute list above the grouping grids) says to add a new Contextual Filter for this block (override). When the filter value is not available, 'display a summary', sort by alphabetical, unformatted, display record count and display items inline. This isn't working as predicted, here is what the tutorial says should be the result: Image 1 in the diagram (h ttp://imgur.com/l9TbLyv). My content continues to look the same as it did previously in the exercise, i.e. like this: Image 2 in the diagram. However when I put "S" into the Preview with contextual filters, I get: Image 3 in the diagram. I was asked for screenshots, so without contextual filters is h ttp://imgur.com/zXCnsvA and with "s" in contextual filters is h ttp://imgur.com/7DF6UUD .

When I created the new contextual filter in Part 4, I got a copy of what was in the Page, so I have two contextual filters, both with Taxonomy term: Name. If I delete the first contextual filter from the block, then my preview shows the same information as Image 1 in the diagram. I think I'm missing something &/or the blog post is unclear. Should I have started "this block override" with 0 contextual filters? I.e. Should I have started by deleting elements from the page which were copied into the block?

Part 5 instructs to "Add the alphabetical list on our page with the grouped terms and Go back to our Page display".

I've got the view working correctly now. The thing which stumped me was that adding a block created an entire copy of the original page which (philosophically) I don't understand. When there's a page and a block override which give instructions about the view, how does drupal know which instructions to pay attention to?

Thanks to all the folks who have helped.

I am posting here in return, my block configuration, you will see that your contextual filters differ from mine, and for that matter, from what the tutorial describes.

Whatmore, the tutorial from Kristin Brinner describes in "Part 4. Create A-Z list" how to set up this block, which is what I did and got the expected result.

I would suggest you go through that part in the Tutorial again, the block you have at the moment is not configured according to the instructions of the tutorial.

And a useful quote from the Views 3 Handbook (accessible via Advanced Help):

  Each display can have its own settings, but when created, a display
  will take all of its basic settings from the default display which all
  Views must have. For most settings, there is an override button that
  will override that single setting for the current display. Overridden
  settings will have a mark in the summary for that display. All
  'default display settings' are shown in the other displays in
  'italic'. When you override a setting, then it is shown 'normal'.

Will keep an eye on this post! Best of luck!


Modify custom search box added in page.tpl.php My Drupal theme (Nexus) doesn't have a search bar in the header.
So added a custom header in page.tpl.php using the following code.

 <?php if ($search_box):?>
<?php print $search_box ; ?>
<?php endif; ?>

I wish to modify the search-box a bit, so I added the following lines
to nexus_form_alter function in template.php.

if ($form_id == 'search_block_form') {
    print $form_id;
    //$form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibility
    $form['search_block_form']['#size'] = 20;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search Site'); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit']['#attributes']['alt'] = "Search Button"; //add alt tag
    unset($form['actions']['submit']['#value']); // Remove the value attribute from the input tag, since it is not valid when input type = image

    //$form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/icon-search.png');

// Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search Site';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search Site') {this.value = '';}";
  }

But the above piece of code doesn't have any effect on the search box that appeared on the top. I suppose that since I have manually printed the search
box at the header, hook_form_alter may not be of any use to me.

Can anybody suggest how to change my search-box characteristics.

I have finally resolved this one using a jquery which I have applied
to the element using JS Injector Module.

jQuery(document).ready(function($) {
  $('#edit-keys').attr('size', '20');
  $('#edit-keys--2').attr('size', '20');
});


What is the custom date format to display Days or Months ago in date field? I want to display # Days Ago, or # Months Ago, or # Years Ago

Example: 3 Days Ago

I need to add custom symbols in the Date field in views.

I think it's best for you to use the Timeago module: https://www.drupal.org/project/timeago

First, it provides a timeago date formatter option for use with dates anywhere, which answers your need.

Second, it solves the caching and correctness of time-ago dates problem for you automatically. Even though you don't mention this in your question, this is important as it's best to cache pages in live production in one way or another.

Good luck.


Notice: Undefined index: field_brand_image in include() in views field template I've got another question about undefined index that I can use help with.

The error message I get is: Notice: Undefined index: field_brand_image in include() on line 15

I'm pretty sure that this is the same lnaguage and "und" portion of the field array issue I had in my other question here: Notice: Undefined index: und in include()

And only displays when the field is empty

Except this time the error is coming from a views template, the line throwing the error looks like:

php print $fields['field_brand_image']->content;

I "think" the answer involves an isset conditional, but I don't know what the syntax should be.
I'm using D7.23 and views 7.x-2.3

I'd appreciate some help.
Thanks.

One way of doing that is using a empty to check the field as following:

<?php print (!empty($fields['field_brand_image'])) ?
  $fields['field_brand_image']->content : ''; ?>


How to create a Search API block? I have a search view based on "Search API", I want to replace the default search block of the drupal core with a block "Search API".

1) How to modify the search block of the heart so that it uses search api instead ?

or

2) How to create a custom block /structure/block/block-content to use "Search API" ?

You should create an exposed filter for the View page, probably based on the full text search field, and then set the filter form to show in a block.

All can be done from within the Views UI on the edit form for the search page.


How to show a block between the body and a paragraphs field? For a larger article content type on a Drupal 8 page, I want to have the following structure:

Title Image/Video

Body (the normal node body with the title and some text)

A contanct block

Paragraphs

For the title image/video I'm not sure yet whether I want to simply create 2 different article types or find some magic to do either the one or the other, but that's fine.

The body that comes next, will just follow as is and contain some introductional text. I guess, I have to write my own template to be able to place the image before the title, but that'll work.

Then, I want a simple block that contains some simple contact information (probably the same block in every article).

Then, there should follow a paragraphs field that'll hold several paragraphs for the rest of the article.

Do you have any ideas how I could place this block?

Thank you in advance for your help :)

Enable "Layout builder" module first. On "Manage display" in entity config Default "Custom display" enable "Full content", then go there and enable "Use Layout builder" and "Allow each content item to have its layout customized."

This will give you "Layout" tab in each node (of this type where you enable this in config) for ex. - how to arrange each field of this entity, also ability to add custom block, user fields, etc. If you want Contact form there you should probably have to write custom block in custom module and put the form inside - just to have it for placement from the Layout builder.


Share users database from one Drupal database with other Drupal Installs (separate databases, not just prefixed tables in the same db) I have several Drupal databases and core sites currently. What I want to have is several Drupal databases that share a common users database under one core site source. The reason I want this is so that I can restore a sites database from any date I choose without rolling back the other sites content as well. I have looked into prefixing but it sounds like all sites have to be under the same database, the same seems to be true of domain access.

Instead of using table prefixes, you can use a reference to another database as a prefix. For example, core database holds the shared users / permissions, drupal_website database is your actual website.

$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'drupal_website',
    'username' => 'db_username',
    'password' => 'db_password,
    'host' => 'ip_db_server',
    'prefix' => array(
         'default' => '',
         'users' => 'core.',
         'users_roles' => 'core.',
         'sessions' => 'core.',
         'role' => 'core.',
         'role_permission' => 'core.',
         'authmap' => 'core.',
    ),
);

Minor drawback, your database needs to be stored on the same mysql server and each database uses the same credentials (username / password) for the connection.


Views: greater than a date expose filter How can I only show the nodes that are greater or equal to the selected date from expose filter on views?

I'd like to have a dropdown/expose filter which allows me to select the nodes that their post dates are greater or equal to (past week, past month, past six month)

In Views, add a filter of Node: Post date.  You should see something like the image below (without example values changed):

Click Expose to have the filter exposed to your users, choose the operator Is greater than or equal to and choose how you want to filter the results (by inserting a date to be greater than or equal to or entering a value of "-6 months", etc).  This won't present a dropdown, but it will certainly add the filter you need for your view.


Enable placeholder translation for exposed filters I'm building a multilingual site using Drupal 8 and I already managed the creation of a search tool using Views and Exposed Filters. My issue is with the translation of this tool: Drupal gives me the option for the translation of most of the elements of the view, but I can't find any options to translate the placeholder used in the exposed filter.

Is there any way to translate placeholders for those filters?

I'll post the solution I worked out just in case someone might need it. Using the hook_form_alter() function:

function YOUR_THEME_form_alter(&$form){
  if($form['#id'] == 'your_form_id'){
    foreach ($form['#info'] as $filter_info) {
        $filter = $filter_info['value'];
        if ($form[$filter]['#type'] == 'field_type' && $filter == 'field_title') {
            $form[$filter]['#attributes']['placeholder'] = t('your_placeholder');
        }
    }
}


Is there a way to pass a form #value to the form #action in Drupal 7 form API? In the example below I want to take elements from the form and include them as part of the URL that I am submitting the form (using #action) so the submitted URL would look like http://example.com/name_storage/John/Lewis/123412341234.

    <?php

function my_module_menu() {
  $items[‘testform’] = array(
    'title' => 'First Last Name',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form'),
    'access callback' => TRUE,
    );
  return $items;
}

function my_module_form($form,&$form_submit) {
  $form[‘first_name’] = array(
    '#title' => t(The first name of the person),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form[‘last_name’] = array(
    '#title' => t('The first name of the person'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['passcode'] = array(
    '#title' => t('Passcode for this domain.'),
    '#type' => 'textfield',
    '#value' => '123412341234',
    '#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => ‘Submit,
    '#type' => 'submit',
    );
  $form['#action'] = url('http://example.com/name_storage/' . $form['first_name']['#value'] . '/'. $form['first_name']['#value'] . '/' . $form['passcode']['#value']);
  return $form;
}
?>

In FAPI, #action changes the form's action parameter, which, you should not override if you want to make Drupal handle the submission.

In your case, you need to define a custom submit handler and redirect the user in that function. You could do something similar by changing the form's method to GET, but it is not possible to define a complex path like the one you want.

Remove this line:

$form['#action'] = url('http://example.com/name_storage/' . $form['first_name']['#value'] . '/'. $form['first_name']['#value'] . '/' . $form['passcode']['#value']);

Then, add a new submit handler like this:

function my_module_form_submit($form,&$form_state) {
  $values = $form_state['values']['first_name'] . '/'. $form_state['values']['last_name'] . '/' . $form_state['values']['passcode'];
  $form_state['redirect'] = 'name_storage/' . $values;
}

To set the redirect parameter to an external URL, you can do this:

$values = 'http://example.com/name_storage/';
$values .= $form_state['values']['first_name'] . '/'. $form_state['values']['last_name'] . '/' . $form_state['values']['passcode'];
$form_state['redirect'] = array(
  $values,
  array(
    'external' => TRUE,
  ),
);


save cart for anonymous user after registration I know drupal commerce let anonymous user create cart and in billing or shipping step create a user according  billing or shipping information,But I want implement another policy,user can add product to his/her cart,then when he/she want checkout I want redirect him/her to registration form I provided then after he/she fill information(registration) then he/she can keep on shipping.
I have idea I save cart information in temp variables,after he/she create user add that cart information to him/her,But I don't sure this is the only and best way,anybody has idea about how can I achieve this task?

There is a module called Commerce Checkout Redirect, which redirects an anonymous user to Register or Login page and redirects to checkout on filling of either form, that would come handy for you.


Pop-Up E-mail subscription ( module) or appearing form? Is it possible with a certain module or anything of that nature to have a pop with a subscription email-collector inside?

I'm on the final touch-ups of the site and have basically got this left and a few other things. But there is not really too much on this site that I can find that answers this question directly for a newbie.

You can try the Lightbox2 module

  The Lightbox2 module is a simple, unobtrusive script used to overlay images on the current page. It's a snap to setup and works on most modern browsers.

or the CTools Auto-modal module

  Provides automatic modal support for any hook_menu() paths that have 'modal' => TRUE defined. This makes it easy to add optional modal support in any contrib module and helps reduce the burden on module developers to support modals.


Entity Reference with VBO and Rules I am trying to create a rule which fires after modifying node content. Specifically I want to modify the entity reference field values of all the node entities provided by VBO. So I created a rule and a component as shown in the images below.
My problem is that I can not find a way to empty the entityref list of all node entities before the loop, maybe my whole approach is wrong.

I'm not sure what the Change combine with field action does but if you want to set the value of an entity reference field can't you just use the "Set a data value" action in your product_display loop for the entity reference field?


Getting Error : "You must declare "ids" as a unique array of fields in your source settings." while trying to migrate for paragraph in Drupal 8 I have created a yml configuration for migration from CSV source into drupal using composer. After running the "drush migrate:import mbe_book_paragharphs", I am getting the error as You must declare "ids" as a unique array of fields in your source settings.

I am using migrate_source_csv 8.x-3.1

id: mbe_book_paragharphs
migration_group: mbe_migrations
label: 'Import book paragraph'
source:
  plugin: csv
  path: '/var/www/html/drupal/author.csv'
  header_row_count: 1
  ids: [id]
process:
  field_mbe_title: Title
  field_mbe_author: Author
destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: mbe_book
migration_dependencies: null

I need help on how to resolve this issue

In the YML configuration file, instead of "ids", i was using "keys" before but was getting the same error

As the error message suggests, ids needs to be an array, e.g.

source:
  plugin: csv
  path: '/var/www/html/drupal/author.csv'
  header_row_count: 1
  ids:
    id:
      type: integer

Do note that you're in a YML file here; it looks like you might have tried to use PHP array syntax.


Prevent cron from flushing the cache indiscriminately? I use Drupal 6 with the Cache Backport module, and all the available cache tables are configured to be stored in Redis (similar to Memcached in function for RAM caching). The caching works very well.

I have noticed that the amount of data stored in Redis gradually grows as the cache warms up, which is expected. However, the amount of stored data regularly drops suddenly to almost nothing.

I ran a test by loading up the cache by running a search for the word "the". Usually the amount of data stored in Redis will climb to between 20 and 40 MB on that query. Then, I ran the filter_cron job (I use the Ultimate Cron module and can run the different cron jobs selectively.) The Redis memory immediately dropped to almost nothing. After loading up the cache again to 20 - 40 MB, I ran the system_cron, which instantly resulted in Redis memory dropping even lower than it did on filter_cron. Both of these results are repeatable every time. So obviously both of the system and the filter cron jobs are indiscriminately flushing the Redis cache, which negates the purpose of a cache.

Can I prevent cron jobs from flushing the Redis cache, and if so, how? Is there not effective intelligent cache expiration logic on an individual key basis? Or would the cache system malfunction if I prevented it from being completely flushed by the cron job?

Thanks a lot for the help!

The cache is flushed by the system_cron() module, so basically the only way to stop it happening is to hack the core system module (very bad), or use something like Elysia Cron to schedule that particular cron job to run on a slower schedule. One of the module's features is:

  Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.

It's worth bearing in mind that system_cron() performs some other tasks as well (cleaning up deleted files, clearing the queue and batch tables, etc.), so using this method will slow down those tasks too.

Although it's a bit long winded, and not very future-proof, perhaps the only way to get to a satisfactory solution would be to implement a cron hook in your own module, which performs the tasks of system_cron() minus the cache flush. Then you can schedule the system_cron() to run on a slower schedule that suits your caching needs.


How to change the e-mail output of a Entity type field in a webform I have a content type Agenda. In this content type I can create paragaphs of the type Date. This paragraph has a field date and a field location.
Now people can attend to agenda items by submitting a webform (using the webform module).
In this webform use a Entity type field together with views to make a reference to date paragraphs. This reference works perfectly and creates a select with options showing the name of the name together with date and location. But in the e-mail confirmation I don't see the paragraph fields. Only the name of the node. I want to be able to manage how the output looks in the email confirmations.
At the moment I use [webform_submission:values:agenda] to get the value from the submission.
The way it looks now is:
Node:title > Content type [NID]  But I want to be able to see something like:
Node:title | Paragraph:Date | Paragraph Location
How or where can I change this output?

Because I was in quite a hurry, I ended up creating hidden fields in my form for date and location. Using javascript I fetch the information from the Select field and add them to these hidden field. This way this information is send with the submission.
Not the prettiest way to do it but it works.


Select options from JSON file I have JSON file with some id and value, and this need to be populated in form as select list:

$form['select_item'] = [
      '#type' => 'select',
      '#options' => $list,
      '#title' => $this->t('Choose'),
      '#required' => TRUE,
    ];

What is the best way to approach this. Can I somehow convert this JSON in array or something and use it in options?

I would like to have this values form JSON in separate file and to use it from there.

Any idea?

Drupal doesn't have a lot to help with this, it's really a general PHP task.

If you're determined to use the API for it, just load the file data in any way you like (fopen, file_get_contents, etc), and use Json::decode() to turn it into an array.


How to alter a form element to include it inside a fieldset I am using field_attach_form() to display an entity's form. When I call this function, it automatically builds the form, which does not contain any fieldsets, just ungrouped form elements.

Before the form is displayed I would like to take some of the form elements and group them into fieldsets. If I have something like this:

$form array:
    form element 1
        attributes
    form element 2
        attributes
    fieldset1
        attributes
    fieldset2
        attributes

Is there a form element attribute or special function that will allow me to tell Drupal to automatically place "form element 1" into "fieldset1"?

Alternatively, can this be done at the core/entity level, not the custom module, so that when field_attach_form() is called the fieldsets are automatically created?

This code might help you out.

   $form['date_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Select Start and End dates'),
        '#collapsible' => TRUE,
//        '#tree' => TRUE,
    );

    $form['date_fieldset']['date_inactive_start'] = array(
        '#title' => t('Start date'),
        '#type' => 'date_popup', // Provided by the date_popup module
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '0:+1',
        '#required' => TRUE,
        '#size' => 8,
        '#default_value' => date('Y-m-d', time()), // Default value must be in 'Y-m-d' format.
    );

    $form['date_fieldset']['date_inactive_end'] = array(
        '#title' => t('End date'),
        '#type' => 'date_popup', // Provided by the date_popup module
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '0:+2',
        '#required' => TRUE,
        '#size' => 8,
        '#default_value' => date('Y-m-d', time()), // Default value must be in 'Y-m-d' format.
    );


Are there any working Form Modules in Drupal 8 yet? Webform doesn't work yet. Eform won't send emails yet (because rules isn't ready yet). Drupal's built in Contact form sends an email but doesn't save the entries or let you redirect to a thank you page.

Basically I need form builder that saves the results and sends an email - like webform in D7

Is there anything I'm missing or do I just have to wait?

As of 29 mar 2016, there is a dev version of webform, but they're not confident in it enough even to publish it as dev: https://www.drupal.org/node/7404/release?api_version%5B%5D=7234

There's also eform, which is a D8 version of the entityform module: https://www.drupal.org/project/eform

When you're digging through dev versions, a good metric is looking at how many people are using that version-- check the per-version usage stats.  Ideally you want thousands or tens of thousands of sites reporting, but we're not there yet.

For now, I'm hacking the d8's core contact module.  I hope that a more complete solution will be available soon.

People who say you shouldn't use dev modules on production sites are living in the past.  Drupal 7 would have been functionally unusable to a huge chunk of its user base for a long time if no one put dev modules into production.  There are still dev modules that are integral to the function of thousands of substantial d7 sites.  Drupal 8 is nothing but a toy without relying on dev modules-- the form question being an excellent illustration.


Losing superfish menu item after logging out from administration panel I have a superfish menu as my nav menu bar. I customised it and added some pages for each menu item.

When I log out of the administration panel, as a general user I can only see the first menu item, all other menu items are gone.

[edit below]

Right, found out that the problem was because my other three menu items are all link to '.../add/node'. Superfish will not show empty links on the menu bar. However, I actually don't want some of the items link to anywhere as they all have submenu items. I want the link to remain empty so that the user can click on the submenu item. How can I achieve this?

When an item in a menu tree is unavailable because of a lack of permissions, the entire tree below that item will disappear.

You should probably restructure your menu to use placeholders. Have a look at the Special menu items module.


Drupal Solr Remaining is wrong. Why? Using the Drupal Solr admin UI I indexed all queued content.
However, even if everything is indexed and searchable, it indicates, as seen below, that only 2% has been indexed!

Indexed         31084 Items (934.03 MB on disk)
Remaining   30597 items (2% has been sent to the server)
Schema          drupal-4.1-solr-3.x

The problem is that when I want to index the remaining, it starts from zero.
Why is that? Is it a bug?

Indexing is done during cron runs. When you've set up indexing, don't ask for it to be indexed again, unless you want it to start from scratch.

If you want to increase the percentage, and don't want to wait for the next scheduled cron run, run cron manually by navigating to Home » Administration » Configuration » System  » Cron and press Run cron.

If you want to automate this, set up an external cron and trigger it every 10 minutes until indexing is done.

There is no setting to index everything instantly. If that is what you want to do, the answer is that this is not possible. You have to be patient. The reason there is no such setting is because that would put a too heavy load on your system. The system is designed to work the way it works for a reason.


How would you implement a limited time featured node? I am using Drupal 6.

I would like to create for a limited time (start date, end date) another version of a node that would share almost all its properties. This featured version is in fact a recipe sponsored by a company, so we have to put the company logo, etc.

About the only thing that would change is a couple of line of data, another category (keeping the other ones) and the main image.

An exemple of the node I want to create a featured version is here :
http://www.moietcie.ca/cuisine/recettes/entrees-et-amuse-gueules/acras-de-morue

The big difficulty is to have the possibility to create a temporary version. After the date is passed, it must return to normal. Hence, I must keep all the data of the normal version.

I first thought of hijacking the translation system since we don’t use translations and force a fake language: French — Featured. Content without this translation would fallback to French (the normal version).

I did some quick tests, and beside the fact that my admin menu is now in English, it works but I hate my idea. I have to modify core modules of Drupal and I know this is bound to fail at some point.

Do you have any ideas ?

Thanks a lot

I would do the following, but it assume that you use Panels.

Create a panel page.
Add your first node as Content.  Add a Visibility rule, choose PHP, and add in code that checks your date range based on the current time.
Add your second node as Content.  Add a Visibility rule, choose PHP, and add in inverse of the code above.

I wouldn't be surprised if you can also accomplish this with the Scheduler module, but I am not sure how the URL would be handled in this scenario.


What tables should or could be migrated to InnoDB, and which should remain MyISAM? As per title: Is there a quick list of candidates for tables to migrate to InnoDB? And what should remain MyISAM.

Some additional information

The site has a fairly heavy read-load, but inserts approximately 10 nodes per hour, with tags and such.
We make heavy use of CCK (a huge amount of normalised tables in the form of content_field%).
We also use Views for about all our blocks and pages; but many of those are candidate for replacement with custom modules (as to reduce database-queries and the heaviness of those queries).
Users are all anonymous; with the exception of a few logged in editors and webmasters.

You should convert all data to InnoDB to prevent table locking issues. However, here are somethings to think about:
FULLTEXT Indexing
At present, only MyISAM supports FULLTEXT indexing. FULLTEXT indexing for InnoDB is currently in the works for MySQL 5.6 but is not production-ready. If you have any Drupal tables that have FULLTEXT indexes, they cannot be converted to InnoDB at this time.
UPDATE on FULLTEXT Indexing
MySQL 5.6 is now GA (out for Production Use). Please try out FULLTEXT indexing in InnoDB.
To locate those tables that have a FULLTEXT index, run this query:
SELECT table_schema,table_name
FROM information_schema.statistics
WHERE index_type='FULLTEXT';

If no rows come back, convert all InnoDB tables to your heart's content. I wrote an earlier post on how to convert all MyISAM tables to InnoDB using only mysql.
MySQL Replication
If you have a read-heavy environment, reads can go faster in MyISAM if you do the following:

Setup Master/Slave Replication
Create one or more Read Slaves under the Master
Add --skip-innodb in /etc/my.cnf on all Slaves (converts tables to MyISAM when loading data into the Slave)
Change the row format of all MyISAM tables on every Slave to FIXED by this command: ALTER TABLE tblname ROW_FORMAT=FIXED;
I posted something on this in the DBA StackExchange
The book MySQL Database Design and Tuning recommends using ROW_FORMAT=FIXED on pages 72,73. This will internally convert all VARCHAR fields to CHAR. It will make the MyISAM table larger, but executed SELECTs against it will be much faster. I can personally attest to this. I once had a table that was 1.9GB. I changed the format with ALTER TABLE tblname ROW_FORMAT=FIXED. The table ended up 3.7GB. The speed of the SELECTs against it was 20-25% faster without improving or changing anything else.

The only headache with this is making your application aware of separate read slaves.
EPILOGUE
If you are looking at other benefits each storage engine has, check the DBA StackExchange:

Apr 14, 2011 : What are the main differences between InnoDB and MyISAM?
Sep 20, 2011 : Best of MyISAM and InnoDB
May 02, 2012 : Which mysql storage engine to choose?
May 03, 2012 : Which is faster, InnoDB or MyISAM?


Display suite PHP field using tokens I'm trying to use a Display Suite field to wrap an image in a div.

What I also want to do is to htmlspecialchars on the token [node:field_mainimage].

It doesn't want to work for me. Is there any other way I can accomplish this?

Where are those images placed ?

If this is in content type, you can style the content type content by using custom tpl.php files and wrap your images in div there. (in sites/all/thems/yourtheme , that is.)

Also, you can create template files even for fields.

That gives you enormous power of controlling output :) .

It is bit "dirty", but you can also wrap images in div using jQuery. But first method is cleaner.


Drupal Taxonomy in D6 vs D7 I'm building two very big sites using Drupal. Both will have plenty of vocabularies with up to 6-7 levels deep like this:

State->District->City->Area->office name->department

The taxonomy will have multiple parents from across vocabularies.

I'm working on D6 sites and managing taxonomy hierarchy isn't easy and is bit cumbersome with D6.

I want to know if it'd be easier with D7 especially when it comes to managing terms with multiple parents.
Any idea?

The UI for dealing with taxonomy term relationships hasn't changed much in Drupal 7 I think.

However, you might want to look into some contributed projects, for example Taxonomy manager, which exist for both D6 and D7. I don't know if it provides a solution for this, however.


What happened to the arguments part of views 3? Am I just blind?

(I'm trying to pass the current page's nid into a block where I'm theming a view and want to filter the view by the nid.)

They have been renamed "Contextual filters," and they have been moved in the third column that is collapsed by default.

In Drupal 6 (Views 6.x-3.x-dev) the URL arguments are still called "Arguments."


How to prevent my site to crash when adding video content using the Media Colorbox module? I'm having a lot of issues when trying to set up my Media Colorbox module.

For images, the Colorbox module works just fabulous, but whenever I try to add some video content in this Colorbox overlay, the site just crashes: I get a white screen, and the site just keeps loading. It's like it's looking for a file, but it cannot find it, although the link is correct because the file is actually there. The permissions for the files are correctly set.

I've tried many setups, tips and tricks documented on the Drupal pages, with no luck. What I want to achieve is perfectly demonstrated on this page, and although my code looks exactly the same, my content just wouldn't load.

I'm using the most recent versions of all modules:

Colorbox: 7.x-2.2
Media Colorbox: 7.x-1.0-rc3
File Entity (fieldable files) 7.x-2.0-unstable7

I don't think there is an issue with that.

I've tried any possible CSS class: colorbox-inline, colorbox-load, and colorbox-video. I cannot access those movies by surfing to them, although the path is correct.

Might there be an incorrect link to a video player library or something? Maybe it's the setup of the player and not colorbox, media colorbox, or file entity. Just guessing....


What is Content Construction Kit (CCK) in Drupal What is Content Construction Kit (CCK) in Drupal and what is the purpose of CCK?

It used to be called CCK in Drupal prior to Drupal 7, and came in the shape of a contributed module.  In Drupal 7, most of the functionality of the CCK module was moved into the core and it is now usually referred to as "fields" (or "fields in core").

The purpose of the CCK was to provide a simple UI for adding new "fields" to entities so that new, specific content types could be created by site designers.

In Drupal 7, you do exactly the same thing by adding "fields" (which may be typed) to entities.  A full tutorial about CCK/fields is beyond the scope of this Q+A site, but GIYF (Google Is Your Friend).

Edit: As noted in a comment by jimajamma, the CCK project page has more information and links to tutorials.


How to create a textfield with autocomplete function for the view? My Drupal 8 website is multilingual, and on one of the views I present a list of nodes (titles). On top of the page I need to implement a textfield with autocomplete function, where the user can start typing in the language, and then by choosing one the content on the page will be presented in chosen language.

I have started by creating a custom block:

public function build(){

$block = array(
  '#type' => 'textfield',
  '#title' => t('Choose language'),
  '#autocomplete_path' => '?????',
  '#cache' => array(
    'max-age' => 0,
  ),
);
return $block;

}

What should I write in '#autocomplete_path' => '?????' as the list of languages is not taxonomies. It is coming from Languages module. Could you please help me?

I think no need to create block of view programmatically, You can do it with Views Autocomplete Filters module and views Module:
Try the following steps how to create view with language filter, using autocomplete:

Install Views Autocomplete Filters Module.
Create View with Fields Display add the language field The language of the content or translation.
 and your additional fields:

Add Combine fields filter

configure it like the following:

the result will be like:


Drush not reading config file from top-level /drush folder within Drupal install? I'm trying to have localized drushrc.php configurations and alias configurations per site I'm working on, but no matter what I'm trying right now, drush refuses to find or load my drushrc.php configuration file.

Based on #2 in the example configuration file found here:
https://github.com/drush-ops/drush/blob/master/examples/example.drushrc.php

I should be able to place a drushrc.php configuration file in a top-level /drush folder location:

$DRUPALROOT/../drush/drushrc.php (top-level parent above root folder)

No matter what I'm trying drush never seems to detect the configuration file in this location when I do a drush status in the drupal root folder. Everything works fine if I place drushrc.php within my home folder (~/.drush/drushrc.php) or in a sub-folder of my install (*$DRUPALROOT/drush/drushrc.php). Problem is I don't want there and would like it in a top-level folder above my root install!

Is there a secret to getting drush working based on this ?! I've tried drush cc drush every time I move my configuration around but it's never found!

On Mac OS X if it matters? Please help!

Sorry, there is a typo in Drush preventing this:

https://github.com/drush-ops/drush/pull/1542

This fix should be in the next version of Drush.  Sorry for the inconvenience.


Cache problem: update node I am running a Drupal 7 website with "Cache pages for anonymous users" and "Cache blocks" enabled. Both "Minimum cache lifetime" and "Expiration of cached pages" are set to 1 day.

When I update a node, for example, edit a picture, and visit that page as an anonymous user, the new picture isn't being displayed. When I manually clear the cache the page is displayed as it should be. It's like the cache isn't cleared after the node is updated.

Extract of the API:

modules/node/node.pages.inc

function node_form_submit($form, &$form_state) {
  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);

  // Do stuff...

  // Clear the page and block caches.
  cache_clear_all();
}

Notice that the function cache_clear_all is called after the node is saved, regardless if the node needs to be inserted or updated.

Further inspection of the API reveals the following:

modules/node/node.module

function node_save($node) {

  ...

    // Save the node and node revision.
    if ($node->is_new) {
      drupal_write_record('node', $node);
      ...
    }
    else {
      drupal_write_record('node', $node, 'nid');
      ...
    }

    ...

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

  ...
}

Again, everything seems to be as it should be. The cache is cleared using the Entity API (public DrupalDefaultEntityController::resetCache(array $ids = NULL)).

Nothing seems to be wrong in the code. Maybe the code doesn't clear all of the necessary cache?

The problem is that you have a minimum lifetime of 1 day set. This means cache_clear_all() will not remove entries with a lifetime of less than a day. Try setting this to 1 hour, or something more acceptable for your site (eg, how long between new content or edited content, and when an anonymous user needs to see the content).


How to load fields by target type? I'm having a content type with referenced fields of paragraph type. How to get referenced fields in hook_form_alter?

Here are my fields:

[field_media_audio] => Drupal\field\Entity\FieldConfig Object
        (
            [deleted:protected] =>
            [fieldStorage:protected] => Drupal\field\Entity\FieldStorageConfig Object
                (
                    [id:protected] => node.field_media_audio
                    [field_name:protected] => field_media_audio
                    [entity_type:protected] => node
                    [type:protected] => entity_reference_revisions
                    [module:protected] => entity_reference_revisions
                    [settings:protected] => Array
                        (
                            [target_type] => paragraph
                        )

                    [cardinality:protected] => -1
                    [translatable:protected] => 1
                    [locked:protected] =>
                    [persist_with_no_fields:protected] =>
                    [custom_storage] =>
                    [indexes:protected] => Array
                        (
                        )

                    [deleted:protected] =>
                    [schema:protected] =>
                    [propertyDefinitions:protected] => Array
                        (
                            [target_id] => Drupal\Core\TypedData\DataReferenceTargetDefinition Object
                                (
                                    [definition:protected] => Array
                                        (
                                            [type] => integer
                                            [label] => Drupal\Core\StringTranslation\TranslatableMarkup Object

By what you can see in this var dump the field can hold any paragraph type, so you don't know which fields it may contain.

When you have restricted the field to one paragraph type, then load the field defintions for this type:

$fields_paragraph = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('paragraph', 'my_paragraph_type');


Permit user roles to see node (not via view) based on a taxonomy I have some content type with a term reference field (think a magazine site where news are linked to a category).

I must block the node view for a user role, but I don't want to set this access for single node (like tac/tac_lite do), but for single category linked to the node (via term reference field). For example I want that role "FOO" can see node of category "BAR" but not nodes of category "XYZ", where "BAR" and "XYZ" are terms od f the same vocabulary.

My idea is this:

add a select list field to the vocabolary's fields (and the allowed
values will be the role's ID) so that I can link role to each
category/term
when a user try to access to a node, I check (via hook_node_access() ) that current user's role is available in the node's category fields (that I have setted in previos step).

Is there a better way ?

M.

You can do your own implementation of hook_node_access in a custom module. It passes you the node and the user object, so you can check for certain criteria, and limit access appropriately.

http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7


How to expose only one form in views? I have created a view with two exposed forms based on filter criteria and the sort criteria. I would like to display the sort criteria in the actual view and the filter criteria as a block.But when i save the view i get these two forms either as a block or as a view content.
Can any one help me to display the filter criteria as a block and the sort criteria as a actual view?

I would suggest that you clone the view and amend it to display only the filter criteria that you require.  You can then display the cloned view in a block and the original in a page, or wherever you require it to be.


How to make View setting changes happen simultaneously with deployment of a template Making View setting changes happen simultaneously with deployment of a template. Where can I look to solve this problem?

Is there something that puts Views settings into Version Control, like Subversion?

You can export a view, via the views interface or the Features module. Both will version control the view, updating the view but chaining/updating the code (if no alterations have been made in the UI).

What I usually do, is to use a script that

Updates the code on the
Reverts features
Clears cache
Runs cron

This is done calling drush commands and works very well for updating sites that doesn't rely heavily on cached data.


Drupal Pay user for X amount by Admin I have this project that an agent(user) is having a commission on every product that they are selling. The admin should pay the commission through the back end side by using the payment information (paypal email or any) provided by the agent.

What module should I use on this one?

Checkout the Commerce Affiliate module that is used with Drupal Commerce (or UC Affiliate if you're using Ubercart).


A redirect doesn't work in user form The project it's in Drupal 8.2

Hello, when a user fill the profile and Save  ( /user/id/edit) the page it's reloaded with the new data in the same url, but I want to redirect the user to /user/id

This code should work:

function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form_state->setRedirect('user.page');
}

But it doesn't work, any idea what's going on?

Thanks

You need to add a new submit handler to the form:

function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'custom_user_submit_handler';
}

Inside the new submit handler set the redirect:

function custom_user_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form_state->setRedirect('user.page');
}


Can I initialize the broken view mode? In a bundle of content types, I placed fields on many vertical tabs of the field group.
In order to switch display / non-display of the field, I moved and saved it without going well for each tab.
Movement of many fields and field groups at one time was not very easy.
t was saved with tab items and fields that do not belong to parent tab.
After that, even when tabs and fields were moved and saved, there was no change.

I think that the View mode is broken.
I also copied the broken view mode to default.
Therefore, all the view modes are deleted, the newly created view mode is copied from the broken default and remains broken.

Is there a way to restore the default view mode for a particular bundle?

Environment:
Drupal 8.5.6,
Field group module 8.x-3.0-beta1,
Display Suite 8.x-3.1

Export the config and open the view mode in a text editor or run this drush command from the command line:

drush cedit core.entity_view_display.node.[content-type].default

Then remove the field settings you think could break your view mode and import the config again or exit/save if you used the drush command.


Order pending but credit card charged drupal commerce I am using authorize.net gateway and when I have done test runs myself everything is great. But we had our first order today and was only notified when saw authorize.net charge. The credit card charge went through BUT Drupal commerce shows order as PENDING. and no email is sent, what could this be? Is there a final step they are not completing but still after payment? This is strange.

The answer is you need to set the workflow to set the order as completed. Commerce out of the box takes the safe route and assumes nothing about your shopping cart workflow. There is an email that can be configured in Rules for the order confirmation.

The order confirmation email is sent by the rule named Send an order notification e-mail that is under the tag Commerce Checkout in the Rules UI.

To update the order as completed you will need to create a new rule to set the order as completed based on your business rules. It can be as simple as setting the order as completed upon successful completion of an order.

You can use the event Completing the checkout process which will trigger after a successful card charge with Auth.net module or any of the other payment modules, Conditions are none for a simple checkout, actions are Update the order state, data selector is commerce-order then "Order State" is "Completed".

Here is a visual of the rule:


Clearing cache breaks site I'm trying to load a production site in a dev environment using the site's codebase (core 8.3.7, contrib and custom modules and vendor folder) and the current database.

After struggling a bit with it, I managed to import the DB (it's PGSQL with a lot of extensions), and the site was up. I looked into the status report page and besides a few update warnings, there are no errors.

First time I try to clear cache, the site breaks and starts complaining about missing modules (one of them made sense, the other is the basic_auth module, which is in core). I manually cleaned up the missing one from the DB, but I'm getting a log of PluginNotFoundExceptions, which to me, says I must have done something wrong. I've tried importing the DB again and I traced the caching issues down to router cache and views cache. All of the other caches are cleaned with no issues, but these two throw the above exceptions.

I've tried to install the codebase again via composer, respecting the .lock file with composer update --lock, and it says there is nothing to install/update.

I'm a bit lost, and the only way I can make the site work (even if momentarily) is by importing the DB again, but it breaks after cache clearing and/or configurations being exported, either via drush or via backend.

AFAICT, even if the codebase was in fact missing something (ie, someone installed something in production not managed by composer), it would show up in the contrib folder and by importing the DB it should be fine, right?

Does anyone have some suggestions on where to start looking for the problem?

Are you sure there are no differences in the codebase? This would explain the issue. The plugins/routes are cached in the database until you clear the cache. Then they are rediscovered from the codebase and the missing plugins or routes become visible. It's not necessarily that the code is missing physically, it can also be a problem with autoloading.

If there is a problem with syncing the codebase by git/composer, use another tool, for example rsync. Make sure to sync the complete codebase, also the files in the root folder.


Exposed filter selectbox dropdown for a textfield I have a textfield for one of my content types and there are many unique results for it. I am trying to create a View of this content type of this textfield as an Exposed Filter with a list of all the unique results from this textfield. Views by default only gives you a textbox for you to search through these results, but if you don't know what to look for, it doesn't work too well.

How would I expose this textfield of all the unique results in a selectbox in a view?

You can use Grouped filters of exposed filters to set unique results for select box in a views. Please see the screenshot given below:


Administration page doesn't show pop-up (overlay) windows When I try to place new block by clicking "Place block" button or when I click "Configure" on the block I see no pop-up window as I see in tutorial videos, like here: https://www.youtube.com/watch?v=D2KvCGGtBuk 3:10 and 4:25. It seems that this problem is persistent in other administration menus (like views, when I try to choose view format). How do I enable them? Why aren't they shown?

I'm on Drupal 8.1.1, with Nginx web server, Ubuntu 14.04 x32, DigitalOcean. There are no errors in status report except not protected configuration files and trusted host settings, which will be solved when site opens to public.

The block layout is in the standard installation of drupal. This popup should work out of the box.

When you press the button "Place block" this ajax is used:

/admin/structure/block/library/mytheme?region=header&_wrapper_format=drupal_modal...

So I would check first if this ajax is fired and second if there are any js errors in the browser debug tool (F12).


Why is the block template for User Login not used on user/login page? If I dpm() the theme_hook_suggestions in template_preprocess_block on a standard page with the user login block on it, I get block_user_login as a suggestion.

If I go to user/login (while logged out), I don't get any pertinent suggestions. It doesn't even seem to use block.tpl.php when renderedon user/login. I know it's actually rendering that block because it prints out the description I gave it.

The user_page() function returns the form directly (i.e. not in a block) for the user login page. As such it won't fire template_preprocess_block and your dpm() call will never run. If it wasn't called directly in this manner then the User module would inadvertently become dependent on the Block module being enabled, and this shouldn't be the case.

Also, just in case it helps: dpm() will only print out a message for users who have the correct permissions to view them. By default this doesn't include anonymous users.

If you want to change it (temporarily of course, anonymous users really shouldn't have access to variable printouts), go to http://mysite.com/admin/people/permissions and make sure the Anonymous User role has the "Access developer information" permission ticked.