texts: How to use different domains for multilingual sites and keep users logged in?

texts:
I have a site that is in French and English. I am able to successfully setup so that users can switch back and forth between the two domains to view either language, however I cannot seem to keep users logged in. When they are logged into the english domain and then switch to the french domain they are required to login again. However if they switch back to the english domain they are still logged in.

As an example we'll use www.english-domain.com as the base (default) domain and www.french-domain.com as the secondary domain

In settings.php I have modified the following, however it doesn't seem to be keeping them logged in. Am I missing something?

/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on its full domain name. If you have multiple domains pointing at the
 * same Drupal site, you can either redirect them all to a single domain (see
 * comment in .htaccess), or uncomment the line below and specify their shared
 * base domain. Doing so assures that users remain logged in as they cross
 * between your various domains.
 */
$cookie_domain = 'english-domain.com';

Note: That I have also flushed both site and browser cache as well as deleted any cookies left on my machine.

Update:

Here are my language settings:


texts: Set the width of the select box in Drupal form

texts:
Currently I have a select box in a form as follows :

$form['fieldset']['event_trigger'] = array('#type' => 'select',
    '#title' => t('E-mail event trigger'),
    //'#default_value' => $edit['mail'],
    '#size' =>20
    //'#options' => select_eventtrigger_dropdown(),
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
  );

But here #size attribute is not fitting my requirement. It should have been the width of the select box.  How can I achieve this or is there any workaround?


texts: How do I get Crumbs to use the dynamic title from a view?

texts:
I have a view set up with a:
Content: Has taxonomy term ID (with depth)

When I preview I see the title...

However in Crumbs when I go to the DEBUG tab for the view url:

How do I get Crumbs to recognise this Title from the view??


texts: Running drush up to several sites folders at once

texts:
In my server's root folder I have the folder www that contains sites of all my websites. All of these are Drupal.

Navigating into each folder and doing drush --no-backup up -y each time, can be both time consuming and tiring.

Is there a way to update all sites at once, with drush, instead of installing third-party software (like Ansible, IINW).

The command drush --no-backup up -y @sites won't help in this case, as it is aimed for multisites, and I don't work with multisites at all.

Update 1 - Note (might not be relevant when you read this question):

<?php
$aliases['mine'] = array(
'site-list' => array('@site1', '@site2')
);

The file containing it should be putted under public_html (or www) with permissions as 755 or 644.


texts: Exclude Views field from displaying and just print it in field template?

texts:
I have a field (title) in my View that I want to print in another views field template, using:

print ($fields["title"]->content);

However, when I use the above code, the field now prints twice. So I tried to Exclude it from the display in Views, but then my above print stopped working. How can I exclude the field, but still print it somewhere else??

Thanks for the help

P.S. I am referring to Views fields, not Content Type fields.


texts: "global" keyword does not work from within drush script

texts:
I have the following script:

<?php

$GLOBALS['foo1'] = "foobar1";
function g1() {
    echo "g1 " . $GLOBALS['foo1'] . "\n";
}

$foo2 = "foobar2";
function g2() {
    global $foo2;
    echo "g2 " . $foo2 . "\n";
}

g1();
g2();

Running it on the browser gives me:

g1 foobar1
g2 foobar2

Running it via drush scr example.php gives me:

g1 foobar1
g2

Any idea why the global keyword doesn't work when I run the script via drush?

I run this on a D7 site with PHP 5.3.5.


texts:
I hear that Drupal can use not only MySQL but also Postgres, MariaDB, and MongoDB.  (Please add here if it can use also some other database.)

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


texts:
This is a real puzzle, if I disable the image field of the display mode of variations, it is still displayed in the shopping cart.

Can someone explain to me how to customize the shopping cart ?

I do not understand. The "Teaser" display mode does not exist and the other display modes are not listed in the view. Why ?


texts:
Now in my site every logged user are able to change his profile fields (standard fields and custom fields). I am searching a way to avoid this capability for every 'normal' users (in other word i want that only the administrator have this ability).

There is a method to do this via code or via frontend?


texts:
If two modules implementing two separate hooks ended up with functions with the same name, could that cause a conflict or problem?

a.module

/**
 * Implements hook_a_b().
 */
function a_a_b() {}

b.module

/**
 * Implements hook_b().
 */
function b_b() {}

c.module

/**
 * Implements hook_a_b().
 */
function c_a_b() {}

c_a.module

/**
 * Implements hook_b().
 */
function c_a_b() {}

Does the scoping prevent that from causing a problem, even though the functions have the same names?

What happens if two modules declare the same hooks, even though they follow the naming scheme and the hook names contain the module names?

a.module

/**
 * Implements hook_a_b_c().
 */
function a_a_b_c() {}

a_b.module

/**
 * Implements hook_a_b_c().
 */
function a_b_a_b_c() {}

x.module

/**
 * Implements hook_a_b_c().
 *
 * It's not clear which of the two hooks this actually implements.
 */
function x_a_b_c() {}


texts:
I have a very treaky question: how can I make an image to be downloadable in different sizes? This mechanism is required for my photogallery website.

Example:

image field

you can also download this image in:

2000x1000 - these are the links to a specific image size
3500x1500
4000x2000
resolutions


texts: How can override the title markup on a node page?

texts:
I've managed to implement a custom page template but it still uses the default title markup.

I'm trying to find out how to replace the markup around the title so I can change it to something like:

Node title

Subtitle

Can I override a template like region--header.tpl.php or something similar?

I'm using an omega based custom theme too btw.


texts:
I can create a node using the following code:

$node = \Drupal::entityTypeManager()->getStorage('node')->create($array);

But if I have the node ID, how can I edit a node?


texts: In Drupal Commerce how do you auto login an anonymous user that has completed checkout?

texts:
I have Drupal 7 Commerce core installed and configured manually. Not kickstart.

Currently after completing a Commerce checkout (Paypal Express) with an anonymous user, I get redirected back to the "Checkout Complete" page. The page gives a link to Review My Order, but it asks for login details which I do not have since it was an anonymous checkout.

Is there a way to auto login the user after the Successful Checkout?


texts: How to create an ajax auto-refresh table?

texts:
My current situation:

I have an entity list builder for my own custom entity type. I need to make this rendered table to refresh himself (the whole table) each X seconds (5 maybe).

How could I achieve this?


texts: Image field: Force at least/exactly two images per field

texts:
I can easily set the maximum number of elements per field, but is there an easy way to specify the minimum value?
For now, I have an Image field, and I want at least two images.


texts:
i want to modify a Select option field of webform with hook_form_FORM_ID_alter(), but when I do something like:

$form['submitted']['dia'] = array(
'#type' => 'select',
'#title' => 'Dia',
'#options' => $options_first,
'#default_value' => $selected,
'#ajax' => array(
  'callback' => 'ajax_example_dependent_dropdown_callback',
  'wrapper' => 'dropdown-second-replace',
),
);

all the other values are replaced and also the weight.

I only need to add 'options', 'default_value', and 'ajax'. If I remove other properties like, 'type' the field is not displayed, and the other properties like weight is removed if I do what is in the code. How to modify these 3 attributes?


texts:
Well, I'm finally ready to put my five-site multi-site installation online. This community has been a great help in getting me to this point. So thank you all for that.

I'm a bit nervous about the gotcha's that await me in this next step -- discovering differences in operation between my local environment and the one online. I'm running XAMPP on my computer with Apache 2.4.10, PHP 5.6.3, and MySQL 5.6.21. Drupal core and all modules are up-to-date. In addition to each site's database, there is an extra db that is accessed by all sites for common data. For the online system, I plan to select a host company from the list on the Drupal.org, so I can expect them to have all the right stuff. I plan to get a shared server account.

In my current ASP sites (which these Drupal sites will replace), I've been able to develop the sites entirely on my local computer and then just upload the files to the online server and I don't think I've ever had a problem with any differences in operations. My scripts are set up to detect whether they are running locally or online and adjust certain things (such as inter-site URLs accordingly). I've attempted to develop things in Drupal to work that way too, but I'm not sure if there are differences I don't yet know about. I'm concerned about this because on the ASP sites I never had to instal any software. The server company instals whatever is necessary to run the site and I just uploaded files compatible with their software. But in Drupal, I've had to instal Drupal over again for each site, so I'm a bit unsure about how this will translate to the online environment.

So one question I have: Is it possible to simply FTP the entire Drupal folder plus the MySQL database to an online server and have a functioning set of sites, or do I need to go through the installation process on the online computer again for each site?

The doc page on Migrating a site says that it is for single site and that migrating multi-sites is covered elsewhere, but doesn't say where. Even for a single site, it lays out a 16-step process in which I don't think I'll understand most of the steps until I've done them. In any case, that page seems to say that the answer to my above question is very much NO, that I cannot do this by just copying files over.

Anything helpful to suggest on entering this process?


texts: Using node author information in a module (efficiency)

texts:
Problem

I'm building a module to let users apply to a job. The user goes to a job advert, presses apply and it sends their CV to the author of the job advert.

I have it working, but I'm worried that the way I grab the users email is inefficient and I was wondering if there was a better way to do it.

Current Set-up

I have a custom form with a submit function. I grab the email of the author of the current node using the following:

function jobapplication_form_submit($form, &$form_state) {
    if(arg(0) == 'node' && is_numeric(arg(1))){
            $node = node_load(arg(1));
            $user = user_load_multiple(array(),array('uid' => $node->uid));
        };
    $email = $user['1']->mail;

Is there a way to get the node author email without having to load the entire node? It seems really inefficient (at least to my inexperienced eyes).


texts: Autocomplete not working with Better Exposed Filters + Views Table Filter

texts:
everyone.
I'm using Drupal 7 with all modules updated to the last stable version.

I have a table view in which each column can be filtered through an exposed filter.
If I move the filters to the table header using better exposed filters and views table filter modules, the autocomplete feature stops working (both for entity reference fields and for fields for which I've enabled autocomplete with views autocomplete filter module).

Nothing happens while I'm typing (the throbber doesnt't move too), but with Chrome's network inspector I can see that the correct JSON objects are being retrieved.
I'm sure it's not a theme / css problem, as no element is created in the page and I've checked with different themes.

Has anyone experienced this behaviour?

Thanks


texts: Query URL containing term name instead of term ID on Views Exposed Filters

texts:
I've got a View with an Exposed Filter that shows Taxonomy Terms that are used to filter the content that's going to be displayed as the result.

It's a View that shows recipes based on the filters chosen by the user (Type of Recipe, Type of Meat).

When I submit the form, I get the following URL:

/recipes-view?type-of-recipe=all&type-of-meat=22

The last parameter shows the number 22, which is the Term ID for the value chosen. The URL has to contain the Term Name instead of the Term ID.

Can I change it via hook_views_query_alter() or is it needed to create a custom handler for that?

Thanks in advance.


texts: Downloads restrictions through direct URL

texts:
I am developing one feature in which user will get one pdf from my site, for this I have developed a process below,

1) user will click on the link and form open in popup

2) after submitting the form one link will be  sent to his email address

3) when user clicks on the link one small process of token check will be done and he will get the file

4) second time this link will not work

This whole process is working fine here my question is I want to restrict the user to get my files when user directly hit the URL link like www.mysite.com/files/downloads/abc.pdf

users can only be able to download it through that link which is in Email.

Thanks for  advance.


texts:
I get an error after enabling mongodb module in Drupal 8. I am using Drupal 8.1.3 and MongoDB 8.x-1.x-dev.

I get the following error:

  Argument 1 passed to Drupal\\mongodb\\MongoCollectionFactory::__construct() must be of the type array, object given, called in /var/www/html/d/core/lib/Drupal/Component/DependencyInjection/Container.php on line 268 and defined in /var/www/html/d/modules/contrib/mongodb/src/MongoCollectionFactory.php on line 48, referer: http://localhost/d/admin/modules

I followed all the steps in README.txt. What is causing the error?


texts:
I want to add a block which is created by a view. This block has slider and I need to put between some fields of view.

How can I do this?


texts:
I'm trying to return only the first 200 characters (if there are more than that) from a body field in a Drupal custom module. I've found the general php/mysql solution here:

https://stackoverflow.com/questions/2080860/mysql-sql-retrieve-first-40-characters-of-a-text-field

But when I try to implement it with my SQL query in my custom module it doesn't work (ie. it still returns over 200 characters). Here's my code (see the field I used LEFT() on is LEFT(fdb.body_value, 200) on line 6):

$result = db_query(
"SELECT n.title, n.nid, n.status,
fdfty.field_type_value, fdfi.entity_id,
fdfi.field_icon_fid, fm.uri, fm.fid, ua.pid,
ua.alias, el.field_experience_level_value,
**LEFT(fdb.body_value, 200)**,
fdfr.field_role_value, fdft.field_topics_value,
fdfed.field_event_dates_value,
fdfed.field_event_dates_value2
FROM {node} AS n
LEFT JOIN {field_data_field_type} AS fdfty
ON n.nid=fdfty.entity_id
LEFT JOIN {field_data_field_icon} AS fdfi
ON n.nid=fdfi.entity_id
LEFT JOIN {file_managed} AS fm
ON fdfi.field_icon_fid=fm.fid
LEFT JOIN {url_alias} AS ua
ON n.nid=ua.pid
LEFT JOIN {field_data_field_experience_level} AS el
ON n.nid=el.entity_id
LEFT JOIN {field_data_body} AS fdb
ON n.nid=fdb.entity_id
LEFT JOIN {field_data_field_role} AS fdfr
ON n.nid=fdfr.entity_id
LEFT JOIN {field_data_field_topics} AS fdft
ON n.nid=fdft.entity_id
LEFT JOIN {field_data_field_event_dates} AS fdfed
ON n.nid=fdfed.entity_id
WHERE n.status=:status AND n.type=:resource
AND (fdfty.field_type_value=:webinar OR fdfty.field_type_value=:conference) AND el.field_experience_level_value=:level
AND fdfr.field_role_value=:role
AND fdft.field_topics_value=:topic
AND ((fdfed.field_event_dates_value IS NULL)
OR (fdfed.field_event_dates_value >= CURRENT_DATE()))
GROUP BY n.nid, n.title
ORDER BY fdfed.field_event_dates_value",
array(':status' => '1', ':resource' => 'resource',
':webinar' => 'Webinar', ':conference' => 'Conference', ':level' => $level, ':role' =>
$role, ':topic' => $topic));


texts: Drupal compress (gzip) files attached to pages. How to turn it off?

texts:
Drupal compress (with gzip) on the fly all files attached to pages during sending them to browser.
It takes too much time especially with PDF.

How to turn it off?

Drupal 6

edit:
Drupal do not compress pages on its own (option turned off), but apache does (output coming from php). And I want to stay it that way with exception of application/pdf (also output of php)

Is it possible?

edit2:
I couldn't change apache gzipping settings in .htaccess, but I was planning changing hosting. I've speeded it up a little and problem is gone now.


texts:
I am working on a custom module that will allow remote authentication via an API if a user attempting to log in is not an administrator. The module first does a hook_form_alter and in that function does a database query to see if the username logging in exists, in the users table, and if it does then a check is made in the user_roles table to see if the uid is an administrator. If the user is not an administrator then I do

array_unshift($form['#validate'], 'sgauth_user_form_validate');

Where sgauth is the module name

I then have the following function to use a new validation function

function sgauth_user_form_validate($form, &$form_state) {
  if (!sgauth_authenticate($form_state)) {
    form_set_error('name', t('Sorry, unrecognised username or password. <b>Have you forgotten your password?</b>'));
  }
  drupal_goto('<front>');
}

The validation function sgauth_authenticate($form_state) gets the username and password entered in the login form and make a call to an API and the user is known by the Authentication behind the API a token is returned. If the token is returned I do

user_external_login_register($username,'sgauth');

As I read the Drupal API documentation this should be all I need to enter this user into the users table and to make an entry in the authmap table. If the user_external_login_register succeeds then I return TRUE from the sgauth_authenticate($form_state) function which takes me back to the function sgauth_user_form_validate($form, &$form_state) and to

drupal_goto('<front>');

Which redirects to the site he page with the external user logged in.

All of the above works fine for me. It is probably not the best way of achieving what I need to do and I am always willing to be shown better methods or ideas.

My problem occurs when I enable Modal Forms for Login Links. The login for the local user (i.e. an administrator works fine) However for an external user I get an alert error box

An AJAX HTTP error occurred.

If I OK this error I still have the modal box visible so it appears the function creating the modal box has not completed. The actual login process has completed fine and if I navigate anywhere on the site the modal box disappears and I can work with the external user logged in.

I need to find what I am doing that is causing this error to be thrown and how to fix it. I have spent hours looking for answers in Google and also looking through the Drupal code for the Modal Form and can not see what might cause this issue.

I would appreciate some help in solving this issue.


texts: How to change a fields text_format for admin users, and show a plain_text for anonymous users?

texts:
When a node with body text format as plain_text is posted by anonymous user , how do I change it to full_html when being edited by admin or authenticated user?

Is there anyway I can edit body fields text_format on the go? like through preprocessing or form hooks?

I also have cases where some of the nodes when edited by admin comes with "enable/disable richtext", and for some nodes, it does not show up.


texts: Remove required field in validation form

texts: If I have a multiple field (ajax) required: FIELD_A (N), and I want it not required if: FIELD_B has a certain value. How can I do ? Any function in $ form_state?


texts: Accessing content for a specific node revision via a relationship in Views

texts:
A module I've written implements hooks defined by the Field API to provide a custom field for defining references to specific node revisions by storing vids. (The module borrows functionality from the Entity Reference, Node Reference and Node Revision Reference modules.)

I have a requirement for "parent" nodes to reference a specific version of one or more "child" nodes. The child node(s) may be modified (i.e. new revisions created) after a reference to it is stored against a parent node. It's essential that the reference on the parent node continues to refer to the same revision of the child node unless the reference is manually updated to a newer revision by a user with sufficient permissions.

I'm currently working on Views integration for the field defined by my module. When creating displays containing one or more parent nodes, I'd also like to be able to display field data for any referenced revisions of child nodes. I've defined the following relationship in my module:

/**
 * Implements hook_field_views_data().
 */
function mymodule_field_views_data($field) {
  $data = field_views_field_default_views_data($field);

  // Get database table info for $field.
  $storage = $field['storage']['details']['sql'];

  foreach ($storage as $table_data) {
    $table = key($table_data);
    $columns = current($table_data);
    $id_column = $columns['vid'];

    if (isset($data[$table])) {
      // Relationship: node revision referenced from $field.
      $data[$table][$id_column]['relationship'] = array(
        'title' => t('Referenced node revision'),
        'label' => t('Node revision referenced from !field_name', array(
          '!field_name' => $field['field_name'],
        )),
        'help' => t('A bridge to the node revision that is referenced via !field_name.', array(
          '!field_name' => $field['field_name'],
        )),
        'group' => t('Node revision reference'),
        'handler' => 'views_handler_relationship',
        'base' => 'node',
        'base field' => 'vid',
      );
    }
  }

  return $data;
}

This relationship allows me to display field content for child nodes where the referenced revision is the current revision. However, if an old revision is being referenced by a parent node, the field data is empty. This behaviour occurs when I create a view displaying either content or content revisions.

Does anyone know of a way of accessing field data for a specific node revision via a relationship in Views regardless of whether it's the current revision or not?

Thanks in advance to anyone who can offer any suggestions!


texts: The RTL css file is not working for a menu

texts:
I wanted to make the CorporateClean theme RTL. Every thing is Ok except Main Menu. It effects alignment for both languages. For Persian is also right and for English as well.
As example: I wrote the following code in RTL Css file

#header-menu ul.menu li {
float:right;
dir:rtl;
text-align:right;
}

It makes the menu RTL for both English  and Persian languages.


texts: How can I use the administration theme for the user/%/edit page?

texts: How can I get the user/%/edit page to use the admin theme that is used for the rest of the site?


texts: Updating computed field's value without needing to clear cache

texts:
I have a computed field that lists content related to a node, so it's value should be changed when I add a new node. Whenever, I add a new node I need to clear the cache to update the computed field's value.

How do I prevent caching value of the computed field OR re-compute the value after adding a new node?


texts:
I have a content type of book leave. When the user created the node. I want to check whether the start date is less than or equal to end date. Start date and end date are date fields.

How to acheive this?


texts: Redirecting to external validation page using oauth with drupal_http_request()

texts:
I'm working on a module to integrate with the Piryx API, and per the OAuth documentation, I should be redirected to an external page where the user can allow access to my application.  The problem is that I'm using drupal_http_request():

$response = drupal_http_request($url, $headers, 'GET', $data);

to get the data, and the page markup is returned in $response['data'] instead of redirecting me to the external page (if I put the URL in my browser, it brings up the page fine).  Is there something I can do to redirect to the external URL so the user can allow access, or do I just somehow need to use the markup to display it in my site?

Thanks.


texts: Does deleting a field in a content type remove the data?

texts: A previously posted question appears to assume that the data is deleted in the database if the field is deleted in his/her forum content type.  I think that the field still exists and the data is still available if you add the field back.  I am reluctant to test this out on my current website in case I am wrong :}.


texts: Using '#type"=>'container' to create a div wrapper around nested elements?

texts:
From my reading a render array can define a wrapper div by using the '#type'=>'container'. I am inserting a render array in the page_alter hook function in the page_bottom region. It appears that the container type does not work in this case. The code below does not wrap the two #markupelements with the div wrapper but instead outputs the div then the content at the same level.

$page['page_bottom']["notices"] = array(
  '#type' => 'container',
  '#attributes' => array(
    'id' => array('notices'),
  ),
);

$page['page_bottom']["notices"]['notices-placeholder'] = array(
  '#suffix' => "
",
  '#prefix' => '
',
);

$page['page_bottom']["notices"]['notices-tab'] = array(
  '#markup' => '
NOTICES &nbsp;10
',
);

What I want is the following.

NOTICES....

What I get is the following.

NOTICES....

--- Added
I did try #children earlier in the day and it didn't work as well. Before I left for the day I also tried with

$page['page_bottom']["notices"]['notices-placeholder'] = array(
    '#suffix' => "
",
    '#markup'=>"Empty String", // added to see what it would do
    '#prefix' => '
',
);

This resulted in a completely out of sync html with the #markup tag being outside the #prefix/#suffix. I don't have the results on me now to post but if you try it you will see the results for your self.


texts:
how can I display node info(not only title but all fields) into cart?
Example:
My site has a lot of stores and each store can buy some books.
How can I display stores info into user cart?
Thanks in advice


texts: Clone add_more button in custom content type

texts:
I create a bundle with the paragraph module and add it to a content type.

Is there a way to duplicate the "add-more" button so I can click on it on the top and the bottom of the page? I want to have this button present one in the top of the page and one in the bottom.
I try to deal with the function field_multiple_value_form() but I don't know how to make it works.

I think I express myself badly.

I created a new content type (News) and in it I put a field type (paragraph).
This field can contain as many buttons you want, cannot it?
I want to repeat these buttons at the top and bottom of the News content type, not in the form that structures the paragraph itself as shown on the picture above.


texts:
I'm new to Drupal. My website has been disable due to malicious code found in
/var/www/vhosts/domain.com/httpdocs/sites/all/themes/tao/tao/css.php

What should I remove in this file?
http://pastebin.com/4xQixw13


texts: Rule works but produced "err_empty_response" error when I want to edit it

texts:
So I have created a rule, that works, does what it should exactly do (so the syntax and configuration is okay), but after creating it and waiting a while, the rule becomes un-editable and the edit page gives just WSOP, while disable, export, delete etc still keeps working. I tried manually recreating the rule, it again works and is editable for a while, until it does the same thing.  There is also no error generated on apache when this happens. I also tried it on multiple computers and browsers. I have clean path URL enable though, could that be an issue?
Here is the exported rule code

{ "rules_odeslat_pp" : {
    "LABEL" : "odeslat PP",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail" ],
    "ON" : { "user_update" : [  ] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "account" ],
          "roles" : { "value" : { "4" : "4", "6" : "6", "3" : "3" } },
          "operation" : "OR"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "account:field-pp-odeslany" ] } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : [ "account:field-stav-uctu" ] },
          "PROVIDE" : { "variable_added" : { "pz" : "PZ" } }
        }
      },
      { "data_calc" : {
          "USING" : {
            "input_1" : [ "pz" ],
            "op" : "-",
            "input_2" : [ "account:field-pp-odeslany" ]
          },
          "PROVIDE" : { "result" : { "ns" : "novy stav" } }
        }
      },
      { "data_set" : { "data" : [ "account:field-stav-uctu" ], "value" : [ "ns" ] } },
      { "data_set" : { "data" : [ "account:field-stav-uctu" ], "value" : [ "ns" ] } },
      { "mimemail" : {
          "key" : "vyplata",
          "to" : [ "account:mail" ],
          "cc" : [ "" ],
          "subject" : "Informace o Vaší odměně",
          "body" : "Važený zpracovateli,\u000D\u000A\u000D\u000Aadministrátor webu právě odeslal [account:field_pp_odeslany] Kč do účtárny! Nový stav vašeho účtu na webu Prostudent: [account:field_stav_uctu] Kč. \u000D\u000A\u000D\u000APokud nebudou peněžní prostředky připsány na Váš účet do 15. dne v měsíci, obraťte se prosím na zákaznickou linku a problém rádi vyřešíme.\u000D\u000A\u000D\u000ATento email je pouze informativní, neodpovídejte na něj.\u0022,",
          "plaintext" : "Važený zpracovateli,\u000D\u000A\u000D\u000Aadministrátor webu právě odeslal [account:field_pp_odeslany] Kč do účtárny! Nový stav vašeho účtu na webu Prostudent: [account:field_stav_uctu] Kč. \u000D\u000A\u000D\u000APokud nebudou peněžní prostředky připsány na Váš účet do 15. dne v měsíci, obraťte se prosím na zákaznickou linku a problém rádi vyřešíme.\u000D\u000A\u000D\u000ATento email je pouze informativní, neodpovídejte na něj.\u0022,",
          "language" : [ "" ]
        }
      },
      { "data_set" : { "data" : [ "account:field-pp-odeslany" ] } }
    ]
  }
}


texts: With Drupal Commerce, how to configure product for "on request"?

texts:
I'm sure this is detailed somewhere, but I haven't had an luck in finding an explanation/description...

I have a website based on Drupal Commerce (new version to be released is based on Kickstart 2). I would like to have a product which is available "on request". This differs from my current products, which are either available or not; managed via the Stock module.

Is there some way to set up suitable rules, or even a module, to manage such a situation? Ideally I would like to have a separate button - "on request", for the product display (as can be set-up through the normal configuration for any of the displays) - for such products, assuming it's possible. A customer could order the product, I (or the team) would receive the request, we'd review the order, and have a discussion with the customer about lead time, etc., etc.

Anyone is free to point me in the direction of where this type of functionality is already described! My thanks (and apologies) if this case.

Thanks!


texts:
I am using drupal7 and some basic modules like organic group, views, panel, filedepot etc.

I have two headers as shown in image below. I am not able to understand the problem


texts: We are planning to use NFS mount in place for sites/default/files and will be mounting the NFS on a Linux machine. Once mounted onto server, and linking it with Drupal file system (through Public File System path), are there any other configuration that needs to be taken care of? Please advice


texts:
I started a project that required me to create a site selling tickets to a nightclub for special events.

People attending the event must be able to buy a ticket or multiple tickets, and add a ticket holders name for each ticket. They are then sent a confirmation e-mail with their tickets attached as individual tickets with bar codes.

I tried Ticket but this did not integrate with commerce as easily as I had liked.
I tried the COD distribution which has ticket installed, and their own custom module to link it to commerce. However, I personally don't like distributions. I find they have too much un-needed stuff with them, and I don't like waiting on them to update core when security updates are needed.
I also tried the Commerce Tickets module, which looked promising, but the ticket holder name data was not easily accessible, or available in views. As well as a series of bugs, and a maintainer who seemed non existent, this didnt seem like an option either.
I also tried Commerce Booking but that didnt do what I wanted it to, and  if the cart module is enabled a lot of errors are generated

Therefore I determined my only option was to create the functionality myself, hopefully using only contributed modules, and not too much custom stuff. I am posting an immediate answer to provide help for anyone in the same situation. I am not looking for other answers to this question unless you have something really cool to share!


texts:
I have a weird problem with my new Drupal 7 site. This is also my first Drupal site.

I have now two users: admin1 (has admin rights) & user1
at first, when I logged with admin1, everything was fine
when I logged in as user1, on the hovering admin panel it says that the logged in user is admin1, and this user has admin rights although they don't show on the DB. If content is added by user1, the creator is admin1
I added user2 with no admin rights. Everything went fine until I logged out user2: now the admin1 do not seem to have admin rights anymore but the user2 has them
I tried to disable nginx caching and it seems that it's off, but the problem still remains
Earlier, my site was on LAMP-stack without problems. At least not similar to this. Apache needs too much memory so I switched to LEMP-stack, and this problem arised. So, I assume the problem is somewhere on my nginx-configuration.
All this time, on the database, only admin1 actually have the admin rights

I am using the 7.34 core but the same problem existed with 7.33 as well. The site is hosted on DigitalOcean on a server using Ubuntu 14.04 x64. The webserver is nginx 1.4.6-1ubuntu3.1


texts: How to sort language select list on current language context

texts:
I have a form with a language field with the language select list widget.
The options of this field contains an array with a pattern like

['langcode' => t('language')]

Now I want to sort these options in the right order.

The default sorting is on the value but not on the translated one.

e.g. ['de' => t('german')] which I translated into "Deutsch" will now sort under "g" instead of "d".

So I did try to do it in a form alter hook and a preprocess hook but this is not the right place to do it, because the values are still untranslated here.

So my question is how can I sort these options if the values are translated?


texts: Maintenance page is not loading anything in the head tag

texts:
I have a template based on the Basic theme.

I have created the maintenance-page--offline.tpl.php, and maintenance-page.tpl.php templates in my template folder, using a similar markup as in the page.tpl.php file.

These pages are not loading anything in the <head> tag.

What did I do wrong?


texts: ImageBlock Module- Responsive/Fluid images

texts:
I am using the ImageBlock Module to upload/insert images into a block, which works great! However I am designing a responsive/fluid website. I have no problem with this if the image is stated in CSS, but for some reason I can not get the ImageBlock to treat the image that was uploaded as responsive/fluid.

How can the image that I uploaded to the ImageBlock I created, be responsive/fluid in a website that is designed to be fluid?

Thanks!


texts: Generating pages with multiple views based on url parameter

texts:
I wish to generate pages that populate a series of views of different content types based on a parameter in the url.

For example, a user may navigate to:

www.mysite.com/{tag}

The generated page would find all content tagged with the {tag} parameter and present it as a series of views, for example:

Custom page for {TAG}

View 1                 View 2
Item 1 (type A)        Item 1 (type B)
Item 2 (type B)        Item 2 (type B)
etc                    etc

and etc.

I wish to style and theme the resulting page considerably. Ideally I would also make it possible for an end user to style the resulting page.

I am a little unsure what the best 'drupal' way to make such a page is.

a) Is it possible to somehow style and manage the taxonomy page for 'tag' to look how I want?

b) Should I programatically generate the pages in a custom module that searches for content based on a taxonomy term (not even sure how this would be done)

c) Should I generate a series of views then pass parameters to them on each specific page?

d) Is there some other, better way to achieve such a page in Drupal 8?

One final question, which solution would perform best in terms of page loads, or would they all be pretty similar?


texts: How to add a 2nd submit button to a node form?

texts:
I need to have an extra Save button at the top of my node form.

Pressing the 2nd button should do the same action like the regular one.

The following code creates a 2nd save button:

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

  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );
}

But how do I put it at the top of the page (the form length is not fixed).


texts: How to render / preprocess list of entity reference nodes?

texts:
I hove a content type that editors can 'attach' related nodes to.

When I 'theme' / 'style' nodes of this content type through view mode everything is basically fine: the related nodes are rendered as teasers and I can style them as I like.

Now I need to wrap the list of related nodes in an extra class e.g. 'related-nodes' according to the output of another field. For example the editor chooses 'round corners' from a list field, then the css class "rounded" should be added to the wrapper of the list of related nodes should.

I am aware I can remove the entity reference field from the display settings and preprocess it through template.php. But then how do I preprocess the list in template.php? So far I just don't know how to actually access / handle it.

In devel tab I do get the array of related items. I could of course loop through that array and re-build node by node thruogh node_load – but since I only want to wrap that loop re-rendering each node feels wrong.  Any suggestions?


texts: Private filesystem does fire 403 on every role and file

texts:
Like the title might expect I am not able to view any file that i am  delivering through the private file system. Only if I bypass the access check via role settings.
I tested it a minute ago with a fresh d8.9 installation. Here images are are delivered (statuscode: 200). I my main project I receive a 403. Why is that so ?
Drupal does create the private files and as admin (bypassing) I also can see the file. As non admin (authenticated user) I cannot.
How can I debug this issue?
A theory I have read said something about varnish setting... I searched  the whole project without finding any script mentioning "varnish". I spend now good 6 hours... checked roles, scripts and so on. I could now start a crazy adventure by deinstalling 80+ modules until it might work or somebody could give me a hint how I debug this madness?
Thanks in advance

Guests on the left | authenticated users on the right


texts: How to process form in template when you aren't printing the entire form

texts:
I have a form where I am only printing out certain parts of it because I want to style around them.

i.e.

<?php print drupal_render($variables['form']['field_city']); ?>

However, when I try to submit this partial form, it doesn't work.

This is my submit:

<?php print drupal_render($variables['form']['submit']); ?>

Defined in the form like this:

  $form['submit'] = array(
    '#value' => t('CREATE NEW ACCOUNT'),
    '#type' => 'submit',
    '#attributes' => array(
      'class' => array('form-submit', 'go-to-cart', 'user-register-submit'),
    ),
  );

But because of missing form elements, the form doesn't appear to submit. How do I fix this?

I am trying:

<?php
print drupal_render($variables['form']['form_id']);
print drupal_render($variables['form']['form_token']);
print drupal_render_children($form)
?>

But the first two don't seem to do anything for processing (it returns to the form page with all of the values filled in) and the third reprints the form without any sort of styling.

How do I get the form printed the way I want?


texts: CKEditor 4.2 and Media Module, Has anyone gotten this to work?

texts:
Been trying to create a working mix of these modules and only seem to succeed if CKEDitor is using version 4.0.3 or lower.

Any insight here would be huge. Thanks!


texts: How do I pull content from a view into an array?

texts:
I hav a strange task where I need to pull the content from a (well some) drupal view into an array so I can use that data later. I dont want to display contents right away, but I'll need to access it later.

I have already built the view but it was suggested that I can export the view and then create a module to grab the view data but I have no idea how to do that.

Basically what Im doing, is creating a view to pull say, 9 records of node type "blog" and on the front page, I want to pull that view, throw the results into a json array, and then do stuff with it later.


texts: Changing from a Profile to Standard profile after the installation

texts:
Its possible from moving from a custom profile or a Distro and move to a the Standards profile ?

The reason, I'm asking this is because I build a website with the Recruiter distro. At first everybody likes the workflow of the recruiter, then after a while my client ask me to change the entire workflow of the website. I have change some many things from the distro that is not longer useful to have the recruiter profile. I'm running issues with some incompatibility with some modules that the distro is not running the latest version. And I do not think that I need the distro any more.

I have try to move some modules from the profile/recruiter/module to sites/all/modules and the module does not seem to be working.

So my goal would be to remove the /profile/recruiter and move everything to /sites/all/modules & /sites/all/themes


texts:
When I make a node such as a basic page I have to give it a Title by default. However, the Title also appears on the page when I am viewing it, but I do not want every node I have to come with a title tacked unto it.  For example, on some of my nodes, they are linked to the navigation bar, so it looks funny to see the same name twice when visiting the page.

Is there a way to remove the Title being represented on the page?


texts: How can I programmatically unselect "View published content" checkbox for anonymous users?

texts:
I am using Drupal 8. I want to programmatically unselect the View published content checkbox for anonymous users.

How can I achieve this?


texts: how to use a submit handler which is in an .inc file

texts:
I am adding a submit handler to the drupal commerce submit form:

module_load_include('inc', 'my_module', 'cim_profile');
$form['buttons']['continue']['#submit'][] = 'my_module_create_cim_profile';

The submit handler is located in a .inc file. I assumed that the code above would load the .inc file to be used by the submit, but that doesn't seem to be the case, I keep getting an error that the file isn't found.
When I tested the module include with

 $inc = module_load_include('inc', 'my_module', 'cim_profile');
dpm($inc);

it did print out the path to the .inc file, so I know it was located.

How can I load my .inc in so that it is available for the submit handler?


texts: Halt registration when certain conditions are (not) met

texts:
On registration we have to look up the user-information in a remote database (JSON service), when user is not found there, or when some other error occurs, we want to halt the registration completely.

function foo_user_presave(&$edit, $account, $category) {
  $foo_bar = new FooBarSource($edit["foo_bar_invite_code"]);
  if ($foo_bar->is_valid()) {
    drupal_set_message(t('Fail'), 'error');
    //What now?
  }
}

Problem is that I fear some records are being written already in, or before hook_user_presave. From the documentation:

  A user account is about to be created or updated.

Is it safe to simply do a drupal_goto() to halt the registration? Would that cause orphaned records in the Database? What about other modules implementing this hook: would they break or be confused?

Is this hook the proper hook to determine if a user can register?


texts:
I have uploaded the website on pantheon. Users aren't able to login by using twitter provider on my website. I'm using the HybridAuth module. When I try to login, it shows this error

  Fatal error: Cannot redeclare class OAuthException in /srv/bindings/6349f4db8cd54067ae94453f36acb8ec/code/sites/all/libraries/hybridauth/hybridauth/Hybrid/thirdparty/OAuth/OAuth.php on line 11

How do I fix this issue? I have a Facebook login as well and it works. And both the logins work on local host.


texts: Is it possible to make the output of a taxonomy reference field with multiple values grammatical?

texts:
I have a taxonomy reference field that allows for multiple values.

In Views, when displaying this field, I have configured it as follows:

I was wondering if it's possible to somehow configure Views to make this output grammatically:

EXAMPLE 1

Field label: I like:
Values in node: apples, bananas
Views current output: I like apples, bananas.
Desired output: I like apples and bananas.

EXAMPLE 2

Field label: I like:
Values in node: apples, bananas, pears
Views current output: I like apples, bananas, pears.
Desired output: I like apples, bananas, and pears.


texts: Restricting access to specific nodes for specifc users?

texts:
Using drupal 7 I have implemented hook_node_access but am having real trouble figuring out how to go a step further and achieve the following using hook_node_access_records and hook_node_grants.

For a given content type ('submission') I want to limit users with a particular role ('curator') and an additionally set field in their user profile ('location') to see only nodes that have a specific matching field value set ('location').

So in this case curators from London can only see submissions to the gallery in London rather than see all 'submission' nodes.

Update

I have made some progress here in my understanding. See the code below. My question now is can i do the following to check set a realm and grant id that i can use to lock specific users out?

Below I am trying to set a lock such that any user who has the grant id cannot access the node (this will be a subset of people within a given role) and for everyone else I just want the sites normal configured access permissions to apply.

function hook_node_access_records($node) {

$grants = array();

if ($node->type == 'submission') {

    $grants[] = array(
      // Say this node is in our realm.
      // By convention we prefix the name of the realm
      // with the module name.
      'realm' => 'submission-permissions',
      // Define the grant id - users in the realm must
      // have this grant id to access this node.
      'gid' => $node->field_location[LANGUAGE_NONE][0]['target_id'],
      // Users who match cannot view the node.
      'grant_view' => 0,
      // Users who match cannot update the node.
      'grant_update' => 0,
      // Users who match cannot delete the node.
      'grant_delete' => 0,
      // In the case another module provides exactly
      // this access record, the one with the highest
      // priority wins. Usually leave this as 0.
      'priority' => 100,
    );
  }

}

/*
 * Implements hook_node_grants().
 */
function hook_node_grants($account, $op) {

    $grants = array();

    $role = is_string($account) ? $account : $account->roles[4];

    if (($role == 'curator') && ($op == 'view')){

        // Get the currently looged in users accounts details
        $user_fields = user_load($account->uid);

        $location = is_string($user_fields) ? $user_fields : $user_fields->field_curator_location[LANGUAGE_NONE][0]['target_id'];

        if (!empty($location)){

            $grants['submission-permissions'][] = $user_fields->field_curator_location[LANGUAGE_NONE][0]['target_id'];

        }

    }

    return $grants;

}


texts: Getting all nodes that have a specific term id using EntityFieldQuery

texts:
I have been using the following line to get all the nodes with a term id

taxonomy_select_nodes($tid);

But now I want to sort the output by weight (field_audio_weight - field I created).
How can I achieve the same output using EntityFieldQuery ?


texts: Log profile 2 user info a separate log file

texts:
When a user logs in, I want to log the user information from the Profile2 module in a separate file.

How can I achieve this?


texts:
My basic page is using a wysiwyg editor (ckeditor) which is filtered by pathologic to generate links that uses my pathauto aliases. This is great. My problem is with external links. Somehow, pathologic detect those links as a broken internal link and replaces the external domain with its local domain...

ex: my site is on domain.com and on a page's wysiwyg field I am putting an external link to anotherdomainwehost.com/about/us.

This is changed by pathologic to "domain.com/about/us" which is completely wrong!

How can I fix this? Somehow pathologic thinks that anotherdomainwehost.com is the same web site as domain.com. I don't know why and can't find where are those configured.

I found no where in my installation a way to edit the pathologic settings. I went to the Pathologic page but can't find the provided link. I have no "Pathologic" option in the Content Authoring menu...

I am willing to hack the damn thing, whether it is in the code or in the db if someone tells me where to look!


texts: How to rewrite Views filter URLs when based on an aliased node URL?

texts:
I realize this seems confusing, but let me give some background first ...

I have a node (say node/123) with a path alias (call it: /books).  So if I go to http://example.com/books I'm viewing a page that's already been aliased by Drupal from /node/123.

However, now I put a Views block on that page and that block has an exposed filter. So, when I filter results I end up with an URL that looks something like so: http://example.com/books?type=fiction

Now here's the problem: I want to rewrite the above URL into something like http://example.com/fiction-books

This isn't as easy as it seems:

You can't use the pathauto module to set a new alias.
You can't use a function like hook_url_inbound_alter or even custom_url_rewrite_outbound because the querystring doesn't exist in any of those.

I attempted a rewrite in htaccess, which seems like the best solution, but I can't get anything there to work (I suspect this is because of Drupal rewriting the alias already so the pattern to use there is confusing).

For the record I know almost nothing about rewrites, but I've got this in htaccess which doesn't work:

RewriteCond %{REQUEST_URI}^/books$
RewriteCond %{QUERY_STRING}^type=fiction$
RewriteRule %{REQUEST_URI}^/fiction-books$ [L,R=301]

So, how do I do it? Advice on an internal Drupal-way would be ideal. But if not, then help via an htaccess RewriteRule would be really appreciated.


texts:
I have a Webform which I'm validating implementing the _validate event (i.e. altering $form["#validate"] by adding a custom validator which accepts &$form and &$form_state).

In my code I have something like this:

if ($nombre && !CasabacaS3SValidaciones::validarLongitud($nombre, 30))
{
    form_set_error('columnas][datos_personales][nombre', t('El nombre no debe superar 30 carácteres'));
    //what should I put in THIS LINE, replacing this comment, to add the error class?
}

I have no clue about adding the "error" class (e.g. fields marked as required have class "required", and also class "error" when the field is not set). How can I alter the field (take this example field in the form_set_error and assume input variables are &$form and &$form_state) so I can add the error for display?

NOTE: I'm seeking to add the "error" class to the fields, and NOT to the wrapping divs (i.e. those divs having form-item class).

(If a quick solution involves themes, please attach a link so I can read about because i'm banging my head about drupal yet, i'm a total n00b :s).


texts:
How can I pass a renderable array from within a block?

$block['content'] = array(
  '#theme' => 'image_formatter',
  '#variables' => array('path' => 'hello.png'),
);

How do I pass the variables that image_formatter needs when I use a renderable array from within a block?


texts: How to make a block showing the content entity the author of the node is linked to?

texts:
I have a 'business' content type and an 'information' content type on my page.
The author of the business is the webmaster and from the information the authors are the users of the site. The contenttype 'business' has an entity reference field targeting the users linked to that business

On the 'business' pages there is a block showing the 'information'articles published by the users linked to that specific business. So far no problem.

I would like to have a block on the 'information' pages showing the business the author of that node/article is linked to. The author of the contenttype business is always the webmaster and the author of the article is the user. I think that I don't understand the relationship that I must make to get this correct. The block has to look at the author of the node where the block is displayed and see the business where that user is linked to.

I'm completely blocked getting that done. I'm new to Drupal, there were no serious problems so far. But this I can't get done.I'm missing something in the contextual filters and relationships.


texts: When I POST an image file via rest, response is 201: Object Moved, status is temporary

texts:
I'm attempting to POST images to Drupal 8 via the REST api.  The creation is successful (201) and the images appear in the files list.  However, there are problems. I'm not sure if they are independent of one another of is they are related.

1.The images are created with a temporary status.  Would prefer "permanent".

2.The MIME type is set to "application/octet-stream" and the images don't render.  I've discovered that by chaning the "uri" in the json object I'm posting to be an explicit uri like "public://photograph.jpg", the MIME type gets set to image/* and this work.

This is the code i'm using:

<script>
    function getCsrfToken(callback) {              //get token
        jQuery
            .get('http://vhscms/cms/rest/session/token')
            .done(function(data) {
                var csrfToken = data;
                callback(csrfToken);
            });
    }

    function postImage(csrfToken, image) {         //post image
        console.log(image);
        jQuery.ajax({
            url: 'http://vhscms/cms/entity/file?_format=hal_json',
            method: 'POST',
            headers: {
                'Content-Type': 'application/hal+json',
                'X-CSRF-Token': csrfToken
            },
            data: image,
            success: function(data) {
                console.log('postNode success');
            }
        });
    }

    $('#image-save').click(function() {         //attach fcn to button
        getCsrfToken(function(csrfToken) {
            var $img = $('img[alt="image1"]');  //grab first image
            var imgSrc = $img.attr('src');      //grad base64 source
            imgSrc = imgSrc.replace('data:image/jpeg;base64,',''); //clean
            var package = {
                "_links": {
                    "type": {
                        "href": "http://vhscms/cms/rest/type/file/image"
                    }
                },
                "filename": [{
                    "value": "joggers.jpg"
                }],
                "filemime": [{
                    "value": "image/jpeg"
                }],
                "type": [{
                    "target_id": "image"
                }],
                "uri": [{
                    "value": "public://joggers.jpg"  //forces mime type img
                }],
                "data": [{
                    "value": imgSrc
                }]
            };
            postImage(csrfToken, JSON.stringify(package));
        });
    });

</script>


texts: Should the maintenance template be used when the database API raises an exception?

texts:
I have created a maintenance-page.html.twig template for my site.

The settings.php file says:

  This applies when the site is explicitly set to maintenance mode through the administration page or when the database is inactive due to an error.

However, on my site, this only works if I explicitly turn on maintenance mode. If I intentionally break access to my database by changing the password I get a page with a PDO error, not my maintenance page.

Is this a bug, or am I missing something?


texts: How do I return a Twig template inside the build method of a block class?

texts:
Am new to Drupal and this week I learned quite a bit about module development, and for today the case is:

For my new module, I create a custom block that renders a markup, and from the folder structure, the class looks like this:

Note: fax is the module's machine name.

fax/src/Plugin/Block/FaxBlock.php

<?php
namespace Drupal\fax\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;

/**
 * Provides a 'Fax' block.
 *
 * @Block(
 *   id = "fax_block",
 *   admin_label = @Translation("Fax block"),
 * )
 */
class FaxBlock extends BlockBase implements BlockPluginInterface {

    public function build() {

        return array(
            '#markup' => $this->t('This is just a text initially'),
        );
    }

}

I know that in the build method we can also return a form for instance:

 public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\rsvplist\Form\RSVPForm');
 }

And that we can put HTML inside the array if we want.

Question: how can I instead create a template a return that inside the array?

so, instead of returning a markup like this:

'#markup' => $this->t('This is just a text initially'),

I could have a template somewhere:

This is a great example

and then return the template in the build function.

How can I return a template inside the build method of my block?


texts:
We are using the datalayer drupal module, and am trying to add new data to the data layer dynamically on client side. I can access the dataLayer object within site, and I push custom data to it, but everytime I push something new it creates a new datalayer object. Can I add to an existing object?

I only need the first dataLayer object and want to add more data to it, is that possible at client side with Javascript?

If not, I can just have it as it is, but then am not sure how to access granular information within GTM, for example how do I access the values under entityTaxonomy.sections from GTM?

I am using datalayer module.

Any help is appreciated. Thanks!


texts: Include file with functions in node.tpl.php and execute them on node content

texts:
First at all, I know that this isn't the correct way to do this in D7, but I need to do in this way.

I've included a file in node.tpl.php:

include DRUPAL_ROOT . '/sites/all/themes/mytheme/inc/node_functions.php';

In this included file I have a function which, afterwards I want to call from a node's content-body.

Currently, if I call the function from a node content, I get a WSOD. I also checked if within a node-content the function exists, with a PHP function:

function_exists('name_of_my_function')

but it returns FALSE, so the function no exists in this 'scope'.

In summary, I want a collection of helpful functions included/attached to a node, but I don't want to write the include/require statement everytime I'm creating a node. I only want to simple 'call' those functions. So, how can I do it?

Thanks in advance.


texts:
I´m using an Omega subtheme in D7 and I can´t print all terms inside a specific vocabulary belonging to a node.

I´ve tried:

<?php print render($terms); ?> It prints nothing.

<?php print $terms; ?> It prints this error only: Notice: Undefined variable: terms

And this: <?php print render($content['taxonomy_vocabulary_5']); ?> wich prints nothing.


texts:
I'm using the 'commerce funds' module, there is some default views included, one view shows transaction related to the current user.

/user/%/funds/%/transactions

the view shows three fields from the commerce funds table

Type
Amount
Notes

Type and Amount both had broken handlers

so i've double checked the fields exist in the database

mysql> show columns from commerce_funds_transaction;
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| transaction_id | int(11)      | NO   | PRI | NULL    | auto_increment |
| account_id     | int(11)      | NO   |     | 0       |                |
| uid            | int(11)      | NO   |     | 0       |                |
| reference      | int(11)      | YES  |     | 0       |                |
| created        | int(11)      | NO   |     | 0       |                |
| amount         | int(11)      | NO   |     | NULL    |                |
| currency_code  | varchar(32)  | NO   |     | NULL    |                |
| type           | varchar(64)  | NO   |     | NULL    |                |
| notes          | varchar(255) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

so i then re-exposed the fields in commerce_funds/includes/views/commerce_funds.views.inc

 $data['commerce_funds_transaction']['amount'] = array(
      'title' => t('Amount'),
      'help' => t('The amount of the transaction.'),
  'field' => array(
      'handler' => 'commerce_funds_handler_field_amount',
      'click sortable' => TRUE,
  ),
  'filter' => array(
      'handler' => 'views_handler_filter_numeric',
  ),
  'sort' => array(
      'handler' => 'views_handler_sort',
  ),
  'argument' => array(
      'handler' => 'views_handler_argument_numeric',
  ),
  );

  $data['commerce_funds_transaction']['type'] = array(
      'title' => t('Type'),
      'help' => t('The type of transaction.'),
      'field' => array(
          'handler' => 'commerce_funds_handler_field_type',
          'click sortable' => TRUE,
      ),
      'filter' => array(
          'handler' => 'views_handler_filter_null',
          ),
          'sort' => array(
              'handler' => 'views_handler_sort',
          ),
          'argument' => array(
              'handler' => 'views_handler_argument_null',
          ),
      );

and reverted the view, now the amount field is displayed in the view but the transaction type field is still broken.

can any one point out the mistake


texts: Views: list all nodes based on relationship

texts:
I have a datastructure where "Courses" has many "Activities". I've accomplished this by using entity reference to add a course_field to the activity content type.

I am pretty conused, however, as to how to set up a view listing all activities belonging to a certain course.

I've created a view that displays activities and I've set the relationship on the view to "Entity Reference: Referenced Entity". I am a bit confused though, as to whether I should set it to "Entity Reference: Referencing Entity", but I figured the first one made more sense as activities are referencing courses with a field on the activity model.

Now I set the contextual filter to "Content: Course", but when I preview the contextual filter, typing the name of one of the courses does not filter the activities.

What is the correct way to filter activities according to what course they belong to?


texts: Mocking Settings (settings.php) within Unit tests

texts: Drupal's Settings class is marked final and has no interface, meaning traditional PHPUnit mocking techniques will not work out of the box. Is it necessary to install third-party tools to be able to mock this or is there another way?


texts: On Cron run Open and save all Profile2 based user profiles

texts:
i have a RULES event on "Cron maintenance tasks are performed" and a action is attached to it "execute custom php code"

<?php
$old   = '1 day';
$old = strtotime("now - $old");
$query=db_select('profile','pf')
        ->condition('pf.created',$old, '<')
        ->fields('pf',array('uid','pid','created'));
$result=$query->execute();
foreach($result as $record){
$profile=profile2_load_by_user($record->uid);
profile2_save($profile);
}
?>

Error :

  Recoverable fatal error: Argument 1 passed to profile2_save() must be an instance of Profile, array given, called in /home/test/public_html/drupal_sedco_2/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code on line 9 and defined in profile2_save() (line 292 of /home/test/public_html/drupal_sedco_2/sites/all/modules/profile2/profile2.module).

Any clues .
Thanks


texts:
I have a Form route in a site I am working on that is doing an entityQuery and displaying tabular data with some form elements to provide filtering, but without paging.  For various reasons I can't use Views to do this; a lot of the table cells are complex calculations and don't lend themselves to a proper plugin.

$query = \Drupal::entityQuery('node')
  ->tableSort($headers)
  ->condition('type','foo')
  ->condition('status', Node::PUBLISHED);

if ($filters) {
  // Add more conditions.
}

$results = $query->execute();

and then I essentially just have

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

public function resetForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(FALSE);
}

as my form handlers.

The table sorting works great.  My form and filters work great.

Here's my problem.  When a user clicks on a table header, it is essentially a link to the page w/ a GET query with the sort selection and bypasses the form submission process.  When this happens, the filters get reset.  Can TableSort play nicely and do a proper form submission, or do I need to cookie the form state and do the rebuild manually (as needed).


texts:
I am trying to achieve a multilingual site that shares its content across all the (currently two) languages, so the same content resides under the same term no matter what language is currently active.

I've been told that I should use the i18n module, which I did. So right now I have all the names of the terms translated in both languages, so that is all working as it should.

The problem is that when I change the language to, for example, Arabic, all the term titles are still in English, even though I have a nice list of translated Arabic counterparts.

So the question I would like to ask is: is there a way to get Drupal to replace all the English terms with the Arabic ones wherever a term's name is displayed? (so make it behave as if every term name has been run through Drupal's t() function)

Most people who tried to answer this question just suggested I use the i18n module. So yeah, I already did that. I have the translations for the term names, but when changing the language, the term names are still in English

Any help would be greatly appreciated

Edit: Please note that I am not talking about a specific module here. For example, when I go to the admin panel's "Add Node" page, I have a drop-down box filled with terms that I have translated, with the language set to Arabic, and yet they still show up as English. This goes to show that it does not work with Drupal Core modules, so it is not likely to be caused by a poorly coded module per se.


texts: Drupal Views pager shows last page when higher pager value is entered manually instead of page not found

texts:
I have a view with pager. The views pager is not AJAX and the pager id comes is the URL as
http://d7.local?page=3
There are total of 15 pages in the view.
So the last page is http://d7.local?page=14
Now if I manually enter a pager number which is higher that 14 say 30 it redirects to the last page
Need to redirect the user to a 404 page under this situation.


texts: Can't get Authcache to work with Memcache as backend: Cache Status: "MISS"

texts:
I have tried to set up Authcache with Memcached as backend. But when I use the debug feature I always get Cache status: "MISS". Am I supposed to use the "built in cache backend" allthough I am using Memcached?

My settings.php file:

$conf['memcache_servers']  = array('localhost:11211' => 'default');

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';
$conf['cache_class_cache_page'] = 'MemCacheDrupal';
$conf['cache_class_cache_authcache_key'] = 'MemCacheDrupal';
$conf['cache_class_cache_bootstrap'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned to non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
  $conf['memcache_key_prefix'] = 'test';

  // shared settings
  $conf['authcache_builtin_cache_without_database'] = TRUE;
  $conf['page_compression'] = 1;
  $conf['page_cache_maximum_age'] = 600;

I have configured AuthCache to cache pages for Guests and logged in users. As far as I can see everything is set up correctly by the book, but I still get these messages. I am obviously missing somehting, so please take a look at this. Does it look correct?

The Authcache debug message:

  Authcache Debug Status
  Cache Status: "MISS"
  Page Render Time: "800.09ms"
  Page Age: "2 seconds"
  Settings Cache
  Class: "MemCacheDrupal"
  Cache CID: "http://test.mysite.se/produkter/handinstrument/temperatur"
  Debug Users: ["Tommy"]
  Cache User: 0
  Cache Backends:"authcache_builtin"
  Active Backend: "authcache_builtin"
  Authcache Key: "http://test.mysite.se"
  P13n Clients: "Ajax"
  Active P13n Clients: "Ajax"
  HTML/JavaScript time: 38 ms

In my status report i get no error messages. This is what i get for Authcache and Memcache:

  Authcache hook_authcache_backend_cache_save() implemented:
  authcache_builtin

  Authcache builtin cache backend  Using MemCacheDrupal as cache backend

  Memcache  2.2.0 (mer information)

UPDATE: After hours of trying to find the error, I threw Memcache out and installed File Cache. Which worked like a charm. Pages are displayed incredibly fast, once they are cached. So never mind my question. I will go with the Autchache and File Cache combination.


texts:
I worked on Omega-7.x-3.0-alpha1 and added some fixes to fluid style sheets in rtl mode.

How can I commit them to the drupal.org repository?


texts: How can add Contact-Us-form in custom place of page.html.twig file?

texts:
I need to add contact-us form in the custom place of page.html.twig file in my themplate, I want to add some code like belove:

Contact Us

    <form action="#" method="post">
        <input type="text" name="email" placeholder="Email" />
        <textarea name="message" placeholder="Message"></textarea>
        <button>Send</button>
    </form>


texts: How to change the page of a view block display programmatically

texts:
I have a view with a block display. Is there any way to change the block pager page programmatically?
Currently i am embedding theview using the views_embed_view and i am passing the url arguments. What i need is to pass also the pager index argument also. Is this possible?

Thanks in advance


texts: How to make 2 or 3 xml sitemaps in drupal for example for different taxonomies?

texts: I need to generate 4 sitemaps which differ in content included in them according to certain taxonomies! XML sitemap can generate one sitemap. When I try to generate other it displays error: A sitemap with the same context already exists.


texts: How to have a node which displays & interacts differently with different type of users?

texts:
Title might not be very clear. But to clarify my question, I'll take example of a Book Content Type.

I've 3 different types of users: Authors, Reviewers, Admin. Now this is what I want to achieve:

On the Book Page [a display which is shown to even unauthenticated user], Registered Reviewer submits a review for a book which should appear in Approve Reviews page of Admin, When the admin approves it should Appear in respective Author's Reviews for my books page and when finally the Author approves, it should be displayed on the Book Page.

And the reviewer must have a Submitted Reviews page which should list all the reviews he submitted each showing its present status like:

"Waiting for Admin's Approval", "Waiting for Author's Approval", "Approved"

I don't know how to achieve this.


texts: How do I create an ideogram-based 'features' list on nodes?

texts:
I'd like to create a simple checklist-style list on a node. How can I do this?

I presume CCK is involved. I'm thinking that it would follow some logic like this: the node editor checks applicable boxes for the relevant feaures. If a box is ticked, then an image is displayed in the list (and so on) on the node.


texts: Video Embed Field module - how do I add attribute 'id' to the embed youtube iframe?

texts:
The question is related to DRUPAL modules name is 'Video Embed Field' module.

The default output of this module generated the Youtube iframe embed as set in the config by Administrator. But...

The iframe's attribute can be set only for width, height, src but no 'id'. What I want is to hard-code into the module core and add 'id' attribute into the iframe, so every time I setup the embed field I have an id on the iframe.

I cannot find the place where the module core generate the iframe attribute...

Regards,


texts: Debugging search_api (no results in production)

texts:
I'm using search api, search api autocomplete, and search api pages.

I want a search engine for my taxonomy terms.

I configured the modules in the same way locally, and in production, locally, everything works, in production, the terms are indexed, the search suggestions work, but the search does not return any results.

I have been searching for several hours, I emptied the cache X times, reindexed the terms X times etc. but I still do not get any results.

I sometimes had an error in my journal (not always):

  Search keys are given but no fulltext fields are defined.

However, I have added a fulltext field in my index corresponding to Taxnomy> name.

I am a little hopeless.

Does anyone have any idea where the problem may come from?


texts: How to make Imagefield slideshow display full width

texts:
I use Drupal 7.20 and try to make my imagefield just like PULLANDBEAR.

This is what I've already done: I'm using field slideshow to make node slideshow (this works as I want it to).

Then I want my image on click to open a bigger image that respects width and height (this part is really confusing).

Can someone give me the right directions or clues? I still haven't found the right ones. Maybe I used the wrong keyword(s) to find them? Right now I'm still using a trial and error approach as in the question How to zoom in an image using jquery?


texts: Missing my custom ajax field values by image field in node form alter

texts:
I have created new content type and added two taxonomy reference field (select list) both referenced to same vocabulary "car" and one Image field with cardinality = 6,

In car vocabulary listed brands and models like:

Brand 1
- model 1
- model 2
- model 3
...
Brand 2
- model 1
- model 2
....

In my content type, first reference select list depth setting is 1, so displays only brands,
In Second reference select list (Models) content_taxonomy_opt_groups => 1,

I have created simple module, for altering on node form and creating custom ajax on Brands and Models select list,

When select a brand, models field displays only models of selected brand...

My ajax has worked

Problem is: when upload an image (Ajax upload) and click Publish this error is shown:

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

/**
 * Implements hook_form_FORM_ID_alter().
 */
function car_info_form_car_info_node_form_alter(&$form, &$form_state, $form_id) {
  $brand_options  = $form['car_brand'][LANGUAGE_NONE]['#options'];
  $selected_brand = isset($form_state['values']['car_brand']) ? $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] : key($brand_options);

  $form['car_brand'][LANGUAGE_NONE]['#default_value'] = $selected_brand;
  $form['car_brand'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'car_info_dependent_model_callback',
    'wrapper' => 'dropdown-model-replace',
    'effect' => 'fade',
  );

  $form['car_model'][LANGUAGE_NONE]['#prefix'] = '
';
  $form['car_model'][LANGUAGE_NONE]['#suffix'] = '
';

  if ($selected_brand > 0) {
    $model_options  = _car_info_get_model_dropdown_options($selected_brand);
    $selected_model = isset($form_state['values']['car_model']) ? $form_state['values']['car_model'][LANGUAGE_NONE][0]['tid'] : key($model_options);
    $form['car_model'][LANGUAGE_NONE]['#options'] = $model_options;
    $form['car_model'][LANGUAGE_NONE]['#default_value'] = $selected_model;
  }
  else {
    // Remove default options (All models of brands) if brand not selected
    $form['car_model'][LANGUAGE_NONE]['#options'] = _car_info_get_model_dropdown_options('');
  }

  // $form['#validate'][] = 'car_info_form_car_info_node_form_validate';
}

function car_info_dependent_model_callback($form, $form_state) {
  return $form['car_model'];
}

function _car_info_get_model_dropdown_options($brand_id) {
  if (isset($brand_id)) {
    $car_models_tree = taxonomy_get_children($brand_id);

    $models[''] = t('Select model');
    foreach ($car_models_tree as $model) {
      $models[$model->tid] = $model->name;
    }
  }
  else {
    $models[''] = t('First select brand');
  }

  return $models;
}

function car_info_form_car_info_node_form_validate($form, &$form_state) {
  $car_brand = $form_state['input']['car_brand'][LANGUAGE_NONE];
  $form_state['values']['car_brand'][LANGUAGE_NONE][0]['tid'] = $car_brand;
}

If I dont add image or add image without click on upload button (upload handled when clicked on publish directly) in both way my form is submitted correctly

But if click upload button in image field (Upload handled by ajax), this issue is happened and $form_state['values']['car_brand'] is empty when using ajax image upload.


texts: Ajax callback to create paragraphs on form

texts:
I'm trying to create a way that an end user can upload a csv into a node form and it automatically extracts the content and then creates paragraphs in the form.

I have created a custom managed file class that I'm modifying the uploadAjaxCallback function and it extracts the csv contents and I can set some html under the file field using and ajaxCommand but I want to replace or append paragraphs to the existing field.
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {
    // load the CSV document from a file path
    $absolute_path = \Drupal::service('file_system')->realpath('private://catalogue_import/orders.csv');
    $encoder = new CsvEncoder();
    $data = $encoder->decode(file_get_contents($absolute_path), 'csv');

    // Return the paragraph element.
    $content = '

UID	Email

';
    foreach ($data as $row){
      $content .= '
' . $row['Uid'] . '	'. $row['Email'] .'
';
    }
    $content .= '

';
    $Selector = '.harps-file'; /* See: https://www.w3schools.com/cssref/css_selectors.asp */
    $response = parent::uploadAjaxCallback($form, $form_state, $request);
    $response->addCommand(new HtmlCommand($Selector,$content));

    return $response;

  }

If I return the paragraph field in the response then it replaces the file upload.
Is what I'm trying to do even achievable ?
Thanks


texts: How to use the Rules module to flag a node that has just been created?

texts:
I need to automatically flag a node after it has been published. All nodes of a certain content type will be flagged.

In order to solve that problem, I have installed the Rules module hoping that I would be able to automatically flag the nodes that are created. Rules module does not come prepacked with flag actions.

Is it possible to flag an item that has just been created?


texts: How do I get the Commerce order type programmatically?

texts:
I have two Commerce order types, order_a and order_b, which I created at /admin/commerce/config/order-types.

I'm using Commerce 2 on Drupal 8.

I want to process them differently in hook_commerce_order_presave().

How can I programmatically get the order type?  When I check the entity type, it only has commerce_order, but I want to know what type of commerce order it is.  I can't find a method to get the order type specifically.

Here's the code I am using:

function MYMODULE_commerce_order_presave(\Drupal\commerce_order\Entity\OrderInterface $entity) {
  if ($entity->isNew()) {
    kint($entity->getEntityTypeId());
    die();


texts: Where does views's template files get saved?

texts:
I have created a view for content type = "Article" and have chosen "FORMAT" = GRID

FORMAT

Format:Grid | Settings

Show:Fields | Settings

My question is where does this view related template get saved?

I know Views default templates are located under "/core/modules/views/templates/" folder.

Here is the basic GRID template. How this grid template recognize a specific view that can render fields only of "ARTICLE" content type?

Is there any other template formed using view's machine name and row style?

Where should I place any view template so that it can effect all views of specific content type like "Article".


texts: Deprecated configuration for the temporary files path

texts:
After updating to 8.8.1 I get this warning:

  You are using deprecated configuration for the temporary files path. Remove the configuration and add the following to settings.php. $settings["file_temp_path"] = ".tmp"

But I can not remove the configuration, because the page:
"admin/config/media/file-system" is not editable.


texts: how to map comments in drupal migrate module

texts:
So im migrating comments from a different database to Drupal 7 but i cant understand why this wont work. Im successful with migrating nodes, i only mapped the node fields and somehow its node_revision seemed to have automatically updated too.

But in comments it doesnt work, i know to add a comment these tables are affected in drupal:

comment
field_data_comment_body
field_revision_comment_body

am i missing some mapping here in my code?

$this->addFieldMapping('cid', 'id');
    $this->addFieldMapping('is_new')->defaultValue(TRUE); // i dont know what this thing does

    $this->addFieldMapping('nid', 'mainthread');
    $this->addFieldMapping('pid', 'parent')
         ->sourceMigration('ForumComment')
         ->description('Parent comment.');
    $this->addFieldMapping('comment_body', 'body');
    $this->addFieldMapping('subject', 'subject');
    $this->addFieldMapping('hostname', 'host');
    $this->addFieldMapping('created', 'date');
    $this->addFieldMapping('changed', 'last');
    $this->addFieldMapping('name', 'author');
    $this->addFieldMapping('status')
         ->defaultValue(COMMENT_PUBLISHED);
    $this->addFieldMapping('comment_body:format')
        ->defaultValue('full_html');

    /*$this->addFieldMapping('uid', 'accountid')
         ->sourceMigration('WineUser')
         ->defaultValue(1); */

    //optional
    //$this->addFieldMapping('tid', 'category_id');
    //$this->addFieldMapping('comment_count', 'hits');

    // Unmapped destination fields
    $this->addUnmigratedDestinations(array('uid', 'thread', 'mail', 'homepage', 'language', 'comment_body:language'));

      $this->addUnmigratedSources(array('category_id'));

and is my destination correct? here it is:

$this->destination = new MigrateDestinationComment('comment');

based on my code only the comment table is mapped, i just assumed that the body and its revision will automatically map too like in my migration of nodes.

Help please


texts:
I'm getting a strange issue using the 'Reset your password' functionality in Drupal 8.

Basically, the process works fine up to the point of clicking the Login button on the screen that shows the following message:

This is a one-time login for foobar and will expire on Tue, 20/09/2016 - 15:25.

Click on this button to log in to the site and change your password.

This login can be used only once.

When the 'Log In' button is clicked, the user is taken to a 404 page, with a url similar to:

user/reset/123/1474293937/ukVdmEMWoYablzZHPYJzMa30-p_skkDv06d564V1KHQ/admin

At that point, the user is logged in, and they can go to their 'Edit profile' page and change their password, but it's not very friendly to be presented with a 404 page after being logged in.

Any ideas why this is happening?


texts: How do I pass a false value to a contextual filter on a boolean field?

texts:
I'm inclined to think that I'm dealing with a defect, but I didn't see anything in the issue queue about it, so maybe it is a misunderstanding on my part.

I'm creating a view that will have a number of contextual filters. Some of them are on boolean fields. I've isolated my particular issue to a general problem with contextual filters on booleans, so I'm down to a single contextual filter on one of the booleans.

In the preview with contextual filters box, if I put a 1, I get the expected query:

SELECT node.nid AS node_nid, node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data

LEFT JOIN {node__field_partner_bha_member} node__field_partner_bha_member ON node_field_data.nid = node__field_partner_bha_member.entity_id AND (node__field_partner_bha_member.deleted = '0' AND node__field_partner_bha_member.langcode = node_field_data.langcode)
INNER JOIN {node} node ON node_field_data.nid = node.nid
WHERE (( (node__field_partner_bha_member.field_partner_bha_member_value = '1' ) )AND(( (node_field_data.status = '1') )))
ORDER BY node_field_data_created DESC
LIMIT 10 OFFSET 0

However, if I put a 0, it simply excludes the filter from the query

SELECT node.nid AS node_nid, node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
INNER JOIN {node} node ON node_field_data.nid = node.nid
WHERE (( (node_field_data.status = '1') ))
ORDER BY node_field_data_created DESC
LIMIT 10 OFFSET 0

If I type a non boolean value there, e.g., 'bacon', it will give me the false results, but that seems like a hack.


texts: select nodes whose created date in hours is equal or larger than 48 hours

texts:
I make a PHP routine in which all node is selected and check created date and delete those nodes which is created in last 48 hours or greater.

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n ');

foreach ($result as $record) {

        $createdDate = $record->created;
        $currentDate = time();

        $diff = $currentDate - $createdDate;
        $diff_in_hrs = ceil($diff/3600);

        if($diff_in_hrs => 48)
        {
            node_delete($record->nid);
        }
}

but i think it is a bad approach that i select all nodes (which may be 10000 nodes) and then iterate each node. i am bad in sql but i think there may be sql query through which i can get the same result.


texts:
I am trying to theme the node add/edit form for a custom content type (for example, Album). I implemented hook_form_alter() in the theme.
function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case "node_album_form":
      $form['#theme'] = ['node_album_edit_form'];
      break;
  }
}

That correctly intercepts the node add/edit form and passes it to my theme hook which also finds the correct template.
function mytheme_theme() {
  return [
    'node_album_form' => [
      'template' => 'node_album_edit_form',
      'path' => \Drupal::theme()->getActiveTheme()->getPath() . '/scss/templates/album',
      'render element' => 'form'
    ],
  ];
}

In node_album_edit_form.html.twig, I can confirm that changes there alter only the album add/edit form and that I can remove elements with {{ form|without('advanced', 'footer', 'actions') }}, for example.
What I cannot do is placing the form fields where I want them because I'm not using the right reference to the field.

{{ field_album_title }}

{{ field_artist }}

I tried any of the following, but they didn't work.

{{ field_album_title }}
{{ form.field_album_title }}
{{ album_title }}

How can I reference an entity field in a template file?


texts:
I have a content type "book" that has an entity reference field that references users and pulls in a name.  Users also has fields for a picture and an author website.

I would like to add a block at the bottom of each book node that shows the author picture and website.

What is the correct way to set up the relatioknship and filter when there is no user ID in the URL?


texts: How to add an specific action button in views?

texts:
Is there any way to add a specific action button in view module for an entity I've created programmatically.

More specifically, I want to make a search of my entity in view, and having beside each result of the entity an action button .  Currently,  we can configure 'delete/edit' button. I want to add a specific one.

PS: I'm using Drupal 8 and i created my module an entity with drupal console.


texts: Add panelizer display when create a node programmatically

texts: I create a node programmatically on hook_enable of mu custom module. I have panelizer display for this content type and I want to set when create a node programmatically. Can you help me ?


texts: How can I exclude API keys, passwords, and so on from configuration management?

texts:
I am using Drupal 8 and drush cex to commit my configuration to my repository.

However, I want to keep passwords and API keys out of the repository.  How do I do that? (selectively exclude sensitive information from configuration management).

For example, I'm using the SMTP module, but I noticed that in addition to the SMTP server and sender's name, etc., it also exports the API key to code, which should not be exposed.  I want to manage module configuration with configuration management, but I don't want to commit the key.


texts: I have a view for which I want to expose a filter only to users with certain roles and/or permissions. For users without, I do not want them to be able to use this exposed filter. The documentation for hook_views_pre_render() isn't clear on whether it can be used to modify exposed filters. How would I go about conditionally hiding/removing an exposed filter in code?


texts:
I'm totally spooked about this. Last week I activated the contributed module Translation Overview. All worked great, a very usefull module for my project. Now, one week later, I'm totally unable to find this translation overview in Drupal. I have searched every corner, browsed the web to no avail, I have all permissions, the module is activated...

Where do I find the translation overview?


texts: Exporting content translation to similar server

texts:
I have 2 instances of the same site built using Drupal. Both need to be translated, and most of the work of the translation has been done on site A and we need to take the translations from site A to site B. Site B will have slightly newer content, but not a lot and a new version of Drupal (both sites are/will be 8.6+).

I can export translation but they're just for the interface, the content is not getting exported. Is there a way to export or send the translations in site A to site B without having to translate everything again one by one in site B?

Thanks.


texts: Template destreoyed, Regions lost after Flush Caches

texts:
I did a Flush all caches - and all my Template is destroyed and my own made Regions disappeared, their content showed up as disabled, due to "invalid region"....

It's a production site, it was working well for half a year.....
What's up? What to do now?


texts: Submit button to filter data from table select by selecting on list select

texts:
i'm new on drupal, i've create a module that shows a form (with tableselect, list select and a submit button) the tableselect shows data from the database, but i want to filter what i want to see on the table by selecting what i want from the list select and submit. i've create the submit function (it contains the query with condition) and when i use dsm($form['tableselect'] everything works (filter works), but how can i show the result's select on the tableselect ? because it doesn't change

here's my form :

$form['options_state'] = array(
    '#type' => 'value',
    '#value' => array (
        'all'=>t('All'),
        'Valid'=>t('Valid'),
        'published'=>t('published'),
        'not published'=>t('not published')

        )

    );

$form['state_book'] = array(
    '#type' => 'select',
    '#title' => t('state :'),
    '#options' => $form['options_state']['#value'],
);

// filter submit button

$form['filter'] = array(
    '#type' => 'submit',
    '#value' => t('filter')
    );

and this is my table select (the first one shows all records) ;

$header  = array(
    'book_title' => t('title'),
    'book_state' => t('state'),
);

    $sql = db_select('field_data_field_title','ta');
    $sql->join('field_data_field_state','st','st.entity_id = ta.entity_id');

    $sql
        ->fields('ta', array('field_titre_en_arabe_value','entity_id'))
        ->fields('st',array('field_state_value'));
        $result = $sql->execute();

    $rows = array();

foreach ($result as $res){

$rows [] = array(
        'book_title' => l($res->field_title_value, 'node/'.$res->entity_id),
        'book_state' => $res->field_state_value
      );

}

$form['table1'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty !'),

);

return $form;

}

table1 works, but it shows all records (book published and not published)
now here's my submit function :

function book_form_submit($form, &$form_state){

$cond = $form_state['values']['state_book'];

$header  = array(
    'book_title' => t('title'),
    'book_state' => t('state'),
);

$sql = db_select('field_data_field_title','ta');
$sql->join('field_data_field_state','st','st.entity_id = ta.entity_id');

$sql
    ->fields('ta', array('field_title_value'))
    ->fields('st',array('field_state_value'));

    $sql->condition('st.field_state_value', $cond, '=');

$quer = $sql->execute();

$rows2 = array();

foreach ($quer as $q){

    array_push($rows, array(
        'book_title' => $q->field_title_value,
        'book_state' => $q->field_state_value,

    ));

}
$form['table2'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('empty!')
);
}

Now how can i put result of submit on table1 to show what the query returns ??

Thanks


texts: Node edit form shows cached or previous title while editing node, after updating node?

texts:
When I update a node the revision show changes in values when we see diff but after updating node when I edit node again in node edit from it shows old value ie: cached value.

When I flush all cache then the updated value start appearing in node edit form.

In site no page cache is enabled, no block cache is enabled. But we are using memcache

This does not happens always but starts happening when cache not cleared for few hours but after clearing cache it starts working.

Please suggest what kind of cache is effecting values while editing node titles.

I am using modules as well Title and entity_translation

In my views there is no cache and I am using template file for views nid in which I fetch titles like below which also shows cached version :

$link = node_load($nid);
$link->title_field['en'][0]['value']  // English value title
$link->title_field['fr'][0]['value']  // French value of title

Should I try like this to get rid of cache:

$link = node_load($nid,null,true); // setting true

Please suggest, I have been trying and searching from long time but not able to find solution. It seems like problems with memcache.

Minimum cache lifetime = none

EDIT: seems kind of some similar problem Need to flush cache after node translation

TRIED SOLUTION and this is of no help :

function custom_module_node_update($node) {
  $nodeurl = url('node/'. $node->nid);
  cache_clear_all($nodeurl, 'cache_page');
  cache_clear_all("field:node:$node->nid", 'cache_field');
}

I am not sure this will help in this case or not or while updating translation of node. Please suggest!
Thanks!


texts: Is there a way to retrieve shell variables in Drush? I cannot find anything in Drush API docs. If there is no way, how does one handle environment (dev, staging, testing etc.) configurations? Any help is much appreciated. Thank you.