texts: drupal_http_request as authenticated user during cron

texts:
I have a rule set up that runs during cron. Part of that rule is an action that is supposed to save a PDF (via Entity Print which only authenticated users can access) to my server. It works fine when I manually execute it, but when I schedule it, and it gets executed via cron, I get an access denied error.

I have tried to Safely Impersonate Another User, and have also tried to send cookies with the request (based off the Rules download module), but continue to get access denied errors.

global $user;
$original_user = $user;
$old_state = drupal_save_session();
drupal_save_session(FALSE);
$user = user_load(1);

$headers = array();
if ($cookie) {
  $headers = array(
    'Cookie' => $_SERVER['HTTP_COOKIE'],
  );
}

$response = drupal_http_request($url, array('headers' => $headers));

$user = $original_user;
drupal_save_session($old_state);

Is there a way to execute this drupal_http_request as an authenticated user during cron?


texts: Can't login: user/login redirects to index page

texts:
My Drupal 7 user, user login and admin pages all redirect to the index page. I am unable to login at all. This problem came up recently after the site had been unchanged for months.   I can't think of a single reason this started happening all of a sudden.

http://sohp.us/?q=user
... ?q=user/login
... ?q=admin

Nothing looks funny when I debug in my browser. I have the following details based on my research:

No errors are appearing.
There were no updates, automatic or manual, to the site or modules.
I'm not using Secure Pages, Ubercart SSL, or any other SSL modules that might interfere. The site is pretty basic, simple Zurb Foundation theme, Views, and a couple other small modules, nothing fancy.
$base_url = 'http://sohp.us'; // NO trailing slash!  Is specified in my settings.php file (located in root/public_html)
The Drupal instance was installed through cPanel's Softaculous
I downloaded the default .htaccess for Drupal 7 and replaced the existing one (no changes required).

It seems like the PHP for bringing up the login isn't working correctly, but I could definitely be missing something obvious or compeltely different from what I've been trying. If anyone has any suggestions on things to test out to get myself back in, it is much appreciated.

Thank you.


texts: Using variation values in a template file

texts:
I am building a site that uses Drupal Commerce 2 and I am attempting to build out the product details template. Our product has a variation (field_accessories) which is an entity reference to another product and I am trying to access the title, the images (first one actually), and the link to the product's detail page.

I got the title showing with

{{ product['field_accessories'][0]['#commerce_product_variation'].getTitle() }}

and I can get the sku and price with:

{{ product['field_accessories'][0]['#commerce_product_variation'].getPrice() }}
{{ product['field_accessories'][0]['#commerce_product_variation'].getSku() }}

But I need the images and url link. Based on the available methods from using kint on the product['field_accessories'][0]['#commerce_product_variation'] I tried:

{{ product['field_accessories'][0]['#commerce_product_variation'].get('field_images') }}

and

{{ product['field_accessories'][0]['#commerce_product_variation'].getField('field_images') }}

and

{{ product['field_accessories'][0]['#commerce_product_variation'].getField('images') }}

but nothing is working and all come back with null.

When I do a product['field_accessories'][1]['#commerce_product_variation'].getFields() I see the following:

Any ideas on how to access the field_images and url to that product's page? Thanks and let me know!


texts: How to properly skip apostrophe in db_select?

texts:
In my mysql database I have texts full of apostropes which are used as stress marks. I need to implement keyword search ignoring these marks.

I tested it first by using direct sql in PhpMyAdmin:

SELECT * FROM `drupal_corpus_text` WHERE replace(text, "'", "") LIKE "%sinka%"

It perfectly finds the record containing sin'ka.

But I cannot figure how to do it using Drupal features.

Here is what I try to do:

  $apostrophe = "'";
  $query = db_select('corpus_text', 'n')
    ->fields('n', array('text_id', 'speaker', 'text'))
    ->condition('n.text', '%' . db_like($key_search) . '%', 'LIKE')
    ->orderBy('speaker', 'ASC');
  $query->addExpression('REPLACE(n.text, "'.$apostrophe.'", "")');
  $query->execute();

And here is the error I get:

PDOException: SQLSTATE[42S22]:
Column not found: 1054 Unknown column ''' in 'field list':
SELECT n.text_id AS text_id, n.speaker AS speaker, n.text AS text,
REPLACE(n.text, "'", "") AS expression FROM {corpus_text} n
WHERE (n.text LIKE :db_condition_placeholder_0 ESCAPE '\\') ORDER BY speaker ASC

I cannot figure out how I must properly use all the quotes and the apostrophe mark to make it work.

The symbol used in those texts is U+0027.


texts: Form Errors shown after refreshing the page

texts: I have a custom form, which is rendered in a custom block in drupal 8. Now the problem is when I place some form validation code on the form in validate function it works well but the error message is shown after page refresh. I think this issue is related to caching. when I render that form using routing the error message shows.the problem is when the form is rendered in block.


texts: Can computed fields be added to a custom entity?

texts:
How can the "computed field" contrib module's (drupal7) fields be added to custom entities (based on the entity API module)?

Or will the computed field work with nodes only?


texts:
I am implementing a headless drupal website with json:api as the gateway to get all the data.  I am able to get data by their node ids, but that is only if I knew the node id and type beforehand.  Is there anyway to get the content by just using the url path?

For example, if one visits the url https://mywebsite/article/test I need to be able to use jsonapi to get all the data from that url, but because I don't know what the node id is for that url, I won't be able to retrieve those data.  So, is there a filter I can use for url path using jsonapi?

Edit:  I tried it by using the filter:

https://localhost:8080/jsonapi/node/blog_article?filter[path]=/us/articlepage/testpage&include=field_custom_container

and it gives the following error:

  Invalid nested filtering. The field path, given in the path path is incomplete, it must end with one of the following specifiers: alias, pid, langcode.

Any ideas?

Thanks


texts: Upgrading procedures and what essential directories to copy over?

texts:
When I upgrade my Drupal 7 core I do the following process:

Download and unzip d7 release as d7_upgrade
Delete the sites folder in the d7_upgrade
Move the sites folder from my original site into d7_upgrade
Rename the old D7 folder to d7_old
Rename the d7_upgrade to original folder name
drush updb

Majority of the non-core files reside in /sites for D7.

I know D8 has a different structure, but is the same upgrade process going to be the same? I know I would have to move over /themes /modules /sites

Is there anything else I need to move over? Or is there a better method of doing this? I want to upgrade to D8.3 beta to test on my site.


texts: custom service respond me : 401 Unauthorized: Missing required argument foo

texts:
I have this custom service:

function zbs_services_resources() {
  return array(
    'productQuestionForm' => array(
      'actions' => array(
        'send' => array(
          'help' => 'save a FOO entity via send form',
          'file' => array('file' => 'inc', 'module' => 'zbs'),
          'callback' => '_zbs_productQuestionForm_create',
          //'access arguments' => array('note resource create'),
          //'access arguments append' => FALSE,
          'args' => array(
              array(
                'name' => 'foo',
                'type' => 'struct',
                'description' => 'The FOO to create',
                'source' => 'data',
                'optional' => false,
              ),
            ),
        ),
      )
    )

  );
}

And this little jQuery code in a simple html test file:

$.ajax({
    url: "/rest1/productQuestionForm/send",
    headers: { 'Content-Type': 'application/json','X-CSRF-Token':'MY_WORKING_TOKEN' },
    success: function (res) {
      alert("success");
      console.log(res);
    },
    data : {
      'foo' : 'pippo',
      "type":"page",
      "title":"Page submitted via entity JSON REST",
      "body": {
          "value": "
test
\n",
          "format": "filtered_html"
      }
    },
    type: 'post',
    dataType: 'json',
  });

But when I load the simple test html page I see this in developer suite for the POST url:

  401 Unauthorized: Missing required argument foo

Where am I doing wrong?


texts: Is there a way to use File Field but have it’s directory path be different for different instances of content, instead of the same?

texts:
I’m selling mp3’s via Commerce File/File Field modules and i need these files to reside in different directories based on artist name and album name, etc. For example:

mp3s/some_artist/album_name/some_song.mp3.

so typically a catalog would have numerous dirs.

but by default a Drupal content type only allows a single directory to be specified.

so far the only way to achieve this is to have to continually make changes to the product variation content type.
i have to keep changing the file directory setting

this is not a good solution and limits the amount of bulk uploading i can do at one time.

is there a way to get Drupal to just accept these file references as i input it? to accept any number of different file paths, in the context of bulk import?

(i hope i’ve asked this question clearly…


texts: How to automatically assign a role based on email address domain?

texts:
How do I automatically assign a role to new users based on the email address domain?

For instance if the email address is someone@examplecompany.com, and the condition is that all users from examplecompany.com should always have the role specialclient. How do I acheive this?

I am using Rules, but there are no specific email conditions to be found. Can I create my own Rules Condition? If so, I would be very grateful for any tips on how to accomplish this.


texts:
i would like to send system message to user such as site announcement, notification and etc.

i know the private message module, but it could not differentiate the message is send by the real system/admin or a normal user.

How should i do that??


texts:
A generic basic PHP Application using Symfony uses code similar to the following one.

$request = Request::createFromGlobals();
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);

try {
   $attributes = $matcher->match($request->getPathInfo());
   $response = $attributes['controller']($request);
} catch (ResourceNotFoundException $exception) {
   $response = new Response('Not Found', 404);
} catch (Exception $exception) {
   $response = new Response('An error occurred', 500);
}

$response->send();

In Drupal 8, the index.php file contains the following code.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

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

I tried to search for any usagee of the UrlMatcher class provided by Symfony, but I don't see it being used.

How does Drupal handle the URL? How does it generate the response?


texts: Is there any other way to create a "settings" node without having to create a Content Type?

texts:
I need to create something like a node with settings. This will have custom fields, images, etc... Just like a content type, but without having to create one of them.

Why? I think it's strange having to create a content type when I need to create only one node with that structure.

I know this sounds weird, but just wonder if there is another way?

Thanks


texts:
I have a taxonomy of region names, and a content type of products. Each product is referenced to a region. I am attempting to create a single view that would show the products for a given region based on the url. For example, http://www.mysite.com/[region-name1]/products and http://www.mysite.com/[region-name2]/products should display products referenced to those specific region. Right now I have the view path set to /%/products, and a contextual filter set, but when I attempt to view the products, I get page not found. (It does work when I am previewing the view).

It works when I set the view path to [region-name]/products for a specific region and don't use a contextual filter, but I am trying to avoid having to create a view for each region if there is a way that I can do it once for all regions.


texts: Show nearest locations(market, bus stand etc) of the search result(s) on Gmap Drupal 6

texts:
I am using view(style:map) to show search result on Gmap. It works fine but i need to show nearest locations(market, bus stand etc) of the search result(s). How do I do that?

it is fine if I will get nearest locations(market, bus stand etc) on the search result(s) by clicking a button or something else. Please help.


texts: Find the total amount of multiple products of the same type - Commerce

texts:
I've created a rule that sends a thank you email to anyone who donates less-than-or-equal-to a certain amount (which works perfectly), but I cannot figure out how to pull out the total $ amount of all donations on the order and include it in the email.

If it were guaranteed there would only ever be a single donation line item the issue would be simple.  However, there is no guarantee there won't be more than one on a single order, and there will usually be at least one other line item of a different product type included in the order.  I've searched, but cannot figure out how to, for example, calculate the total donation amount for an order that has 2 donation line items of $10 & $20, plus one or more other line items of a different product type, then put the donation total into the thank you email that gets sent out.

Any / all help will be much appreciated!


texts: I want to edit in admin theme some editing pages like "entityform/*/edit". How can I do that?


texts:
I wish to move the bootstrap theme from the repository
located in the folder theme/custom to be a dependency in composer.json
I've checked that the current version drupal/bootstrap is 3.16
I perform rm -rf web/theme/custom/bootstrap
composer require drupal/bootstrap:8.x-3.16
^^-> wrong syntax and have decided to just composer require drupal/bootstrap
Now I need to downgrade the version of drupal/bootstrap in composer.json
and perform composer update --lock
But I got an error:
Nothing to modify in lock file
Unable to find a compatible set of packages based on your non-dev requirements alone.
Your requirements can be resolved successfully when require-dev packages are present.
You may need to move packages from require-dev or some of their dependencies to require.

  Problem 1
    - Root composer.json requires drupal/bootstrap 3.16, found drupal/bootstrap[3.23.0] but it does not match the constraint.

Any hints would appreciate.


texts: Getting content type data from twig view template

texts:
I have a custom content type, view and block all setup and working properly. When I attempt to use kint to access node or anything else from my block template file: views-view--testimonials--block_1.html.twig i keep getting NULL values returned.

Prior to attempting to customize my block template, in my content-types folder, i had a file to directly access my content type: node--testimonials.html.twig which could access the values like so: {{ node.field_testimonial_author.value }}

My question is, how can I get access to node.field_testimonial_author from my block template file? (which is views-view--testimonials--block_1.html.twig)

I may be approaching this entirely wrong. If so, please feel free to offer any educational resources that will help me out. Coming from Drupal 7 the learning curve here for me is essentially a brick wall.

Thanks in advance.


texts: Implement a custom PHP library into a custom block module?

texts:
I have a PHP class and it's files in the folder:

/var/www/include_php/**the_folder**

How should I include this into Drupal?

ln -sf /var/www/include_php/the_folder /var/www/drupalSite/sites/all/libraries/the_folder

and then do drupal_add_library('the_folder') or something else in my block module?


texts:
I am restructuring a website built with Drupal 7 so I wanted to set up TinyMCE with the Wysiwyg module.
I followed the instruction and installed the plugin in the libraries folder. In the admin interface, I can see that TinyMCE is installed and I configured it.
But I cannot get it to work. The editor doesn't load. I then switched to CKEditor. Same result: the editor does not load.

Looking in the browser JS console, I noticed that the path to get to the plugins is wrong which results in HTTP 404 errors. The problem is that the browser is trying to get the resources at wrong path ie https://mysiteurl.com/news//themes/advanced/editor_template.js instead of https://mysiteurl.com/sites/all/libraries/tinymce/jscripts/tiny_mce/themes/advanced/editor_template.js

How do I fix this? Or is there something I m missing?


texts: recent forum topics on sidebar of home page, recent articles and forum topics on article pages, recent articles on forum page

texts:
I'm having a little trouble finding information to help me figure out what I'm trying to do. Please forgive me, as I am new to drupal's api. I have 3 particular scenarios where I would like a little helpful nudge in the right direction.

1 - I really enjoy having the most recent articles being shown on the front page by default. I would like to know how to have recent forum topics, separate from the recent articles, on the sidebar. Just text would be sufficient. Please tell me this is possible. I've searched for hours looking for some kind of information or maybe a module that accomplishes this.

2 - On the Forum, I would like the exact opposite. I would like the recent articles to be on the sidebar. Just the titles would be sufficient here as well.

3 - On the Article Pages, I would like both recent forum topics and articles on the sidebar.

I'm using the core Forum module, as well as Advanced Forum module. -Edit

Are there global variables I can use to achieve this? This, I'm sure, would help others as well with average time on site, and bounce rate.

--Edit--

As Dooshta mentioned, this can be accomplished with Views. It's so very easy to use!

Also, I noticed that there were disabled blocks already there for what I was looking for. I've enabled Recent Content for Article Topics, Active Forum Topics, and New Forum Topics. Once I'm done styling them on my local Drupal Installation, I'll post a link to my live site  to show an example for this Question!

--Edit--

I attempted using the provided blocks, however, I had a problem with a Configure Block link showing up on both provided forum blocks for all roles except admin. After a little research, I seen that it has been a problem for a long time and there's no simple fix. So I decided to use Views instead.

As I mentioned before, Views is absolutely simple to use. I created an Active Forum Topic Block, New Forum Topic Block, and a New Article Block for use on the sidebar. I couldn't configure the Active Forum Topic Block to display the topics in order with last topic commented on first until after creating it, but it wasn't difficult to figure out at all. the page is informative and organized.

If you would like to see how I used Views on my site, go to Strong Local Business. The New Articles don't display on the front page as intended, however you can see them on the sidebar when viewing an article, as designed.

Thanks again, Dooshta!

I hope this question helps others who may want to achieve the same results.


texts: How to configure Drupal module Commerce Shipping Weight Tariff?

texts:
Due to a missing how-to in the module, i am stuck implementing Drupals Commerce Shipping Weight Tariff module.
I added some weight tariff services and under /admin/commerce/config/shipping/methods I added methods to the shipping matrix. Also i added a physical field for the weight to my products.
And here i am stuck: what's next thing to do?
Any help would be very appreciated!


texts:
I have a constant defined in my migration definition like so:

  constants:
    destination: "private://working_papers/"

There are 30,000 files that will come in as part of the migration. I would like to create directory destinations on the fly, based on source field values or whatever I want.

So:

destination: constants/destination

Would become:

destination: constants/destination/@source_field_value/@source_field_value2

This would be to reduce the raw number of files appearing in a given directory. When I try the above, nothing happens, even though the migration succeeds. The files don't go anywhere.

How can I do this? For reference, here is the field in the process section of the definition:

  field_paper_working_paper:
    plugin: file_import
    source: doc_format_url
    destination: constants/destination
    uid: 1
    rename: TRUE


texts:
I'm facing very strange problem with changing my custom entity's fields. I've a custom entity with id, type, .. , premium, premium_expires_at, .. fields. It was  working without any problems with its own fields (those declared in hook_schema()) till today, but suddenly I changed its fields, dropped premium, and premium_expires_at fields, added new fields with HOOK _update_n function. I see database schema changed, but those deleted fields are still being shown in base table key under field_sql_storage key.. I've already ran update.php (many times), but no luck.. I thought it's a caching problem, so I've cleared all caches manually, and with drush, no luck, cleared memcached data (with telnet), any changes.Every time I'm getting the same error, like this:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.premium' in 'field list': SELECT ... base.premium AS premium... в функции EntityCacheControllerHelper::entityCacheLoad() (строка 101 в файле /PATH_TO_MY_PROJECT/sites/all/modules/entitycache/entitycache.module)

I don't have any premium field in my db schema, but still getting this error, is there any way to solve it?

(I am using EntityAPI with Entitycache and Memcache Storage modules).


texts: How to force users to choose a forum when creating new thread?

texts:
Here is the problem: On a D7 community site, upgraded from D6, users are allowed to create new forum threads using node/add/forum link. In the node creation page ,they have to choose which forum their thread belongs to.

The default forum in the drop-down menu is set to '-None-' . So users who do not choose any forum, end up creating their thread in the 'None' forum, which then appears as the first forum and is obviously not desirable.

I am wondering who to get rid of this annoying problem?


texts: Overriding user edit page with Panels loses the user edit form

texts:
I am using panels to override the user edit page (/user/*/edit) to add a block with a form in it. However I wanted to maintain the existing user edit form, including the password, username, etc. When I overrode the page, I was able to add my block, but lost the original user edit form. I've tried adding the various widgets from the 'User' category (user profile, Profile:Main Profile, etc) on the 'Content' section of the new variant, but they just seem to contain various bits of user information, and none of them add the user form.

How can I add back the user edit form to an panels-overridden user edit page?


texts:
I have installed and configured Shortcode in a D8 project. However, when I try to use a short code like [column] or [button], it gets rendered as is in the node view page.

I have used a block panel in the node view page. And the in the block template I have rendered the body field like {{ content['#node'].body[0].value|raw }}.

However, I have noticed, that if I render the content as a whole like {{ content }}, the short codes gets rendered properly as intended.

What am I doing wrong?


texts: How to display a specific form mode in a programmatically displayed form

texts:
I have a custom entity type, property.  In admin/structure/display-modes/form I created a new form mode for this entity type, machine name is property.property_status.  It only shows one field on the form.

I am now trying to show that form mode on a custom page.  Right now I'm using:
\Drupal::service('entity.form_builder')->getForm($property, 'property.property_status') but I get the error:
Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException: The "property" entity type did not specify a "property.property_status" form class.

Any ideas?  Thanks!


texts: Allow users to register using username in drupal commons throw Integrity constraint violation error

texts:
I'm using drupal commons and I want to allow user to pick his username on registration.

Currently drupal commons does not allow user to choose his own username but generates one automatically.

What I have done so far through hook_user_register_form_alter :

I changed the #type of name (username machine name) from hidden to textfield. This display the field.

$form['account']['name']['#type'] = 'textfield';

I removed the default value

$form['account']['name']['#value'] = NULL;

Now when I try to add a new user, I get the following error message:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, name, pass, mail, signature, signature_format, created, status, timezone, language, picture, init, data, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13); Array ( [:db_insert_placeholder_0] => 824 [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => $S$DgHF.OcL6K0hxQ0A4v.O67r4FUp4kpfeuywOrGHvb4zmoEzjpQrW [:db_insert_placeholder_3] => test@test.com [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => filtered_html [:db_insert_placeholder_6] => 1463562222 [:db_insert_placeholder_7] => 1 [:db_insert_placeholder_8] => Europe/Brussels [:db_insert_placeholder_9] => en [:db_insert_placeholder_10] => 0 [:db_insert_placeholder_11] => test@test.com [:db_insert_placeholder_12] => a:2:{s:7:"contact";i:0;s:20:"l10n_client_disabled";b:0;} [:db_insert_placeholder_13] => 267c9864-8fe0-4cc5-81ef-22bd53befcf8 ) in drupal_write_record() (line 7333 of /home/me/websites/customprojects/mysite.local/docroot/includes/common.inc). Backtrace:
PDOStatement->execute(Array) database.inc:2171
DatabaseStatementBase->execute(Array, Array) database.inc:683
DatabaseConnection->query('INSERT INTO {users} (uid, name, pass, mail, signature, signature_format, created, status, timezone, language, picture, init, data, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13)', Array, Array) query.inc:36
InsertQuery_mysql->execute() common.inc:7333
drupal_write_record('users', Object) user.module:582
user_save(Object, Array) user.module:3912
user_register_submit(Array, Array) form.inc:1519
form_execute_handlers('submit', Array, Array) form.inc:903
drupal_process_form('user_register_form', Array, Array) form.inc:385
drupal_build_form('user_register_form', Array) form.inc:130
drupal_get_form('user_register_form')
call_user_func_array('drupal_get_form', Array) menu.inc:527
menu_execute_active_handler() index.php:21

I understand that it is a duplicate problem on the username field but checking in the database there is no username matches the one I have chosen.
So don't understand the error.

Also, I'm wondering if the fact of having username can have a side effect ?


texts:
I have defined a new user role "Webmaster", and assigned it the permissions to administer forms, menu & menu items and taxonomy terms (all). Going to the admin/structure url still yields an "Access denied".

What permissions do I need set to allow my webmasters access to the admin/structure url?


texts: How to remove spaces and beginning 0 from a contact number in Views PHP view?

texts:
I have tried multiple variations and I cannot get this right. I have a contact number field that is user input; therefore, I need to clean it up so that I can use it in a tel: link on mobile devices.

Users could add numbers using different formats, such as:

021 457 7890
+27 21 567 7089
0214577898

What I want to do (using Views PHP) is to strip the spaces, +27, and 0 at the beginning. My PHP skills are limited, but the confusing part for me is the Value code input and the Output code input and getting this to output correctly.

Note: if there is a non-Views PHP workaround, that would be preferred.


texts: jQuery wrapper function when using Drupal behaviours

texts:
I have been trying unsuccessfully to add Drupal behaviors to an existing and workding JS script file that is wrapped in :

jQuery(document).ready(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
});

I cannot get my behaviours to work.

However I have changed the wrapper to :

(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
})(jQuery);

and now the behaviours work.

What is the difference between the wrappers and can I expect the existing Javascript to continue functioning if I make this change ?


texts: Drupal 8: set (sub) fields of the address field optional (not required)

texts:
I need an address field that allow the user to encode only a country OR a country with some other fields he could choose freely.

I other words, I need an address field without any required field.

To do so, I have tried to alter the widget as explained in some tutorials:

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'address') {
    $element['name_block']['name_line']['#required'] = FALSE;
    $element['street_block']['thoroughfare']['#required'] = FALSE;
    $element['locality_block']['dependent_locality']['#required'] = FALSE;
    $element['locality_block']['locality']['#required'] = FALSE;
    $element['locality_block']['administrative_area']['#required'] = FALSE;
    $element['locality_block']['postal_code']['#required'] = FALSE;
  }

}

Unfortunately, the $element variable is not yet populated with the subfields...


texts:
I work between two servers, and I use one for development and the other for deployment. It’s very easy because I can tell the development one to use the database of the deployment sometimes. What I can't do is upload the images to a third service so both the sites will see the same images.
Do you know any workflow in which this is possible?
Are there any modules that allow you to upload images to an external service?


texts: How add markup and prefix / suffix for computed field

texts:
I want to add wrapper element to CCK computed field in a content type.

I could calculate the value of field but when I use HTML tags in Display Code section the result is not rendered properly.

for example I use this code in Display Code.

$display_output =  '
' . $entity_field_item['value'] . ' Count
';

But the result is not corrected HTML . it seems it is encoded !!

&lt;div class=&quot;row&quot;&gt; &lt;span class=&quot;suffix&quot;&gt;Count&lt;/span&gt;&lt;/div&gt;

Can you tell me what should I do to repair this problem ?


texts: how to include external php file in drupal 8

texts:
I want to merge two xlsx file and download merged file in drupal 8. So i used a PHPExcel library for doing so.

But i am not able to include a PHPExcel.php file in custom controller for that. I used require_once, module_load_include() but does not work for me.

How can i include it . please help.

require_once DRUPAL_ROOT.'/'.drupal_get_path('module','custom').'/src/Controller/PHPExcel.php';

or

module_load_include('php', 'custom', 'src/Controller/PHPExcel');

$file1 = 'ford.xlsx';
$file2 = 'toyota.xlsx';
$objPHPExcel1 = PHPExcel_IOFactory::load($file1);
$objPHPExcel2 = PHPExcel_IOFactory::load($file2);

foreach($objPHPExcel2->getSheetNames() as $sheetName) {
$sheet = $objPHPExcel2->getSheetByName($sheetName);
$sheet->setTitle($sheet->getTitle());
$objPHPExcel1->addExternalSheet($sheet);
}

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="ford-toyota.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1,
'Excel2007');
$objWriter->save('php://output');
exit;

and error is :

Fatal error: Class 'Drupal\custom\Controller\PHPExcel_IOFactory' not found


texts: How to display a list of products in same taxonomy as current product?

texts:
I want to display a list of other products from the currently-viewed product's taxonomy/taxonomies on the product page. It would ideally be a text-only list, and would be limited to five or ten products. I'd rather not go the route of node/entity reference fields, as I have hundreds of products. Yes, it would be more accurate to do it that way, but displaying products based on their taxonomy would be accurate enough for my purposes.

Can anyone tell me how to set up something like this? Perhaps with Views?

Thanks!


texts: How to list the most popular content for different periods of time with Radioactivity?

texts:
I'd like to create a view with the most popular content of the last week, the last month and of all time. I've installed the Radioactivity module and created the three required profiles. While adding a radioactivity field 'Popularity' to my nodes, I had to select one of these three profiles, so I assume that I'll have to add another two radioactivity fields with the other profiles and that I'll end up with three fields

'Popularity (week)'
'Popularity (month)'
'Popularity (all time)'.

Is that correct? If yes, I'm wondering whether I now have to create the same rules for the three fields every time in order to change their value. Isn't it possible to add an action that adds an incident to the three fields at the same time, as the incident-values will be the same in the three cases?

This repetition is not a very big problem, but I'm not sure whether the set-up for what I want to achieve is completely correct, because doing the same work multiple times in Drupal is wrong most of the time.


texts: How can I add a contextual filter with taxonomy term name as entity reference?

texts:
I have a content type "award" which have a taxonomy (product) as entity reference.
I want to add a contextual filter by term name on my view. I tried to use a contextual filter on "taxonomy term name" but it's not working, looks like i'm doing something wrong
I added the field in advanced > relations, that way i managed to make a working filter on the taxonomy term name i wanted, but i need a contextual filter
here is the view :

here is the contextual filter configuration


texts: How do I get content to display using Views and Panels?

texts:
I've created a custom view to display two different content types and now want to override the node display with this new view. I tried using this tutorial to do so with Panels, but I always get no content. Not a completely white screen, just a title and nothing beneath it. I am able to add other content using Panels directly, so I think it must be a problem with the way Views and Panels are interfacing. Any idea what I need to do to fix this?

I have tried:
- changing the output format of the view to 'Panel Fields' (as opposed to 'Content').
- clearing and re-clearing my browser's cache.

I'm using Drupal 7.12, Chaos Tools 7.x-1.0-rc2, Panels 7.x-3.2 and Views 7.x-3.3


texts: Video does not pause automatically when slider change in FlexSlider

texts:
I'm using version drupal 7 to create the "slideshow" to display the slideshow of the video, each video is embedded in its own content item.
When the user starts to play the video, if the video is still playing, click "Next", the slide will advance to the next slide, but the video of the previous slide will not stop playing (all browsers). Then, the user can click to play the next video, and then two videos will be played at the same time. If the user advances to the next slide, they may start playing the third synchronized video, and so on. When the user clicks "Next" to go to the next slide, I want to stop any video that is currently playing.
Can someone provide some simple code to prevent multiple videos on different slides from playing at the same time?
This is my video HTML code:
<video class="video-test" style="width:96%;padding-left:6%;" controls>
  <source src="./sites/default/files/MyGovUC 2 0.mp4" type="video/mp4">
</video>

I have tried to use the below js but doesn't work.
$('.video_test').on('afterChange', function(event, slick, currentSlide, nextSlide) {
  player.pause();
});

https://i.stack.imgur.com/5lgGa.png
Thank you for your help.


texts: How can I automatically flag new comments?

texts:
I have a Drupal 8 site with Flag and Rules modules. How to flag a new comment ?
I want that when a user creates a comment, the comment should be automatically flagged.
I created a type of Flag on the comments and I created a rule with the event "When a new comment is posted".
What should I put in action ?


texts: How to set custom access for a custom page?

texts:
For example, there is a page on the site, created before.

I need to set custom permission for it.

Par example, if a user doesn't have a photo in his profile, he shouldn't have access to page "/forum".

On Drupal 7 it was possible via hook_menu_alter and set access control there.

Could you clarify me, how can I it on Drupal 8 ?


texts: Custom Form using Geofield and linked to a View

texts:
I have created a custom form & block which takes a postcode or suburb value and enters it into a return url (https://my-d8-site.ddev.site/store-locator?field_geofield_distance[distance]=20&field_g[…]ield_distance[origin]=mundaring&tid[]=16&tid[]=17&tid[]=18)
This points at a view (path /store-locator) with the field identifiers field_geofield_distance and tid.
The url is returned through Url::fromRoute. but I cannot get the view to change results when the url is submitted and am getting this error:
Symfony\Component\Routing\Exception\RouteNotFoundException: Route "https://my-d8-site.ddev.site/store-locator?field_geofield_distance[distance]=20&field_geofield_distance[unit]=6371&field_geofield_distance[origin]=mundaring&tid[]=16&tid[]=17&tid[]=18" does not exist.
In Drupal\Core\Routing\RouteProvider->getRouteByName() (line 208 of /var/www/html/web/core/lib/Drupal/Core/Routing/RouteProvider.php).
What are the possible issue areas for me to investigate?


texts:
I'm trying to make about 100 landing pages using taxonomy.

I'm trying to stick to Drupal 8 core features as much as possible.

I created two taxonomy vocabularies, Places and Main keyword.

Now, what I want to do is create landing pages that consist of:

1 place + 1 keyword

Places

London
Paris
Berlin

Main keywords

Apples
Oranges

Combinations (each of these is a landing page using tokens from both keywords in Views blocks [perhaps attached by Layout Builder] to make the page)

London + Apples
London + Oranges
Paris + Apples
Paris + Oranges
etc.

What module(s) should I use to link taxonomy terms from two different vocabularies together like this (preferably, in an automatic way so the relevant pages are automatically generated when I add a new term in either vocabulary)?

I have been experimenting with Views and Layout Builder but I haven't come up with a solution yet.

What I tried

I used the Views "taxonomy term page" view to override the taxonomy term pages; this lets me do what I want for a single term in a single vocabulary, but I want to use two terms in combination from two different categories.


texts: Why is the drupal.org site not using the more recent Drupal version?

texts:
Seems to me that if drupal.org is encouraging people to use Drupal 8, that they should be leading by example and migrate their own site to Drupal 8.

On drupal.org:

<meta name="Generator" content="Drupal 7 (http://drupal.org)">

Is there a reason why they've released Drupal version 8 but they themselves are still using Drupal version 7? Should the fact that they have not migrated give us any suspicious reasons why we shouldn't quite yet?


texts: Image styles not generated during config import

texts:
Situation:
Drupal 8.6.9 running DrupalVM with Ubuntu 16.04, Apache 2.4.18, Php 7.1.26
with default settings except for the location of the drupal site.

I am trying to do a migration of a Drupal 7 multilingual site to Drupal 8.

Plan is to setup the Drupal 8 site with as much settings and modules as possible so I can alter the content during the migration such as migrating a D7-field to a different D8-field.

I wiped the default DrupalVM drupal site so I can start from scratch.
So far I have done a drush site-install with standard profile, enabled some contrib modules that are also in the D7 site (pathauto, search404, etc.) and manually set the necessary settings.
One of them is adding the 'field_image' to the 'Basic Page' content type.
I've exported the settings (Config Synchronization) to the config sync directory.

To start from scratch I run a script that does:

drush si standard
drush en <various modules installed with composer>
drush cset "system.site" uuid <uuid set in system.site.yml>

When I stop here and manually create several page nodes through the UI I can successfully add images and the thumbnails are created accordingly.

When I go on and import the config settings with:

drush cim sync --partial

Everything is imported succesfully and everything looks fine.

However, when I add the same page nodes through the UI the images are uploaded successfully but the image styles are not created. The 'styles' directory stays empty and the Apache logs show:

[Sun Feb 10 20:03:18.426565 2019] [proxy_fcgi:error]
[pid 9432:tid 140423712450304]
(32)Broken pipe: [client 192.168.88.1:59863]
AH01075: Error dispatching request to :
(passing brigade to output filters), referer: http://www.drupalvm.test/node/add/page

(error broken in several lines to avoid scrolling)

No errors in php-fpm logs.

The error seems to point to a bug in Apache 2.4/mod_fcgi, but that has been fixed in 2016.

Also, because the problem occurs after reading in the config settings, not before, I suspect the problem is either related to the config settings or to Drupal itself.

Does anyone have any idea what to check to solve this problem? I'm on this for days now with no success.


texts: Importing Webform Submission List (Text) with Feeds Tamper

texts:
I am exporting Webform Submissions from one Drupal site and attempting to import them onto another site with Feeds.

Unfortunately, the "Select Options" Webform field (that allows for multiple options to be selected) looks like the following in the exported file.

I am attempting to import these results directly into Drupal with feeds. I wish for these to go into one List (Text) field called "Status Desired".

As you can see, these all have different headers and I want them all to go into the same field.

I tried to use the "Find replace" in Feeds Tamper to change the "X" to the correct value but I had no success.

For example, if the user selects all 4 of the options, only the last one is imported.

Is there any way for me to use Feeds Tamper to import this as is into Drupal?

Or will I have no choice but to modify the data in Excel?


texts: Is there a live backend demo of drupal commerce?

texts: Is there a live Drupal Commerce backend demo site?  I would like to take a look before trying to download and install it.


texts: Get node bundle (content type) from EntityInterface

texts:
trying to find if node is bundle article (node bundle = content type) before executing the rest of the statements in the following example

I can test if the entity is node but I can't figure out how to test if content type is article

<?php

use \Drupal\Core\Entity\EntityInterface;

function MODULE_NAME_entity_presave(EntityInterface $entity){

    //if content type is article
    if ($entity->getEntityType()->id() == 'node') {
        //do wonderful stuff ...
    }
}


texts:
I have call my current contactform with this function in mytheme.theme.

$form = Drupal::routeMatch()->getParameter('contact_form');

I have this

object(Drupal\contact\Entity\ContactForm)#412 (23) {
  ["id":protected]=>
  string(8) "feedback"
  ["label":protected]=>
  string(14) "Nous contacter"
  ["recipients":protected]=>
  array(1) {
    [0]=>
    string(21) "mymail@gmail.com"
  }
  ["reply":protected]=>
  string(0) ""
  ["weight":protected]=>
  int(0)
  ["originalId":protected]=>
  string(8) "feedback"
  ["pluginConfigKey":protected]=>
  NULL
  ["status":protected]=>
  bool(true)
  ["uuid":protected]=>
  string(36) "6e997e8b-9d85-4e59-9e43-67004270fe13"
  ["isSyncing":"Drupal\Core\Config\Entity\ConfigEntityBase":private]=>
  bool(false)
  ["isUninstalling":"Drupal\Core\Config\Entity\ConfigEntityBase":private]=>
  bool(false)
  ["langcode":protected]=>
  string(2) "fr"
  ["third_party_settings":protected]=>
  array(0) {
  }
  ["_core":protected]=>
  array(0) {
  }
  ["trustedData":protected]=>
  bool(false)
  ["entityTypeId":protected]=>
  string(12) "contact_form"
  ["enforceIsNew":protected]=>
  NULL
  ["typedData":protected]=>
  NULL
  ["cacheContexts":protected]=>
  array(1) {
    [0]=>
    string(28) "languages:language_interface"
  }
  ["cacheTags":protected]=>
  array(0) {
  }
  ["cacheMaxAge":protected]=>
  int(-1)
  ["_serviceIds":protected]=>
  array(0) {
  }
  ["dependencies":protected]=>
  array(0) {
  }
}

But how can I rendering this ? My goal is to render the current contact form.

Edit1: I have tried this How to programmatically render a contact form in a theme in D8

But when I try this

    $form = Drupal::routeMatch()->getParameter('contact_form');//get the current form called
    $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $form->id(),
      ));
//$form->id() = 'feedback'
        $form = Drupal::service('entity.form_builder')->getForm($message);

I have a very big array (Firefox and Chrome crash when in print them )

When I try this

$form = Drupal::routeMatch()->getParameter('contact_form');//get the current form called
ContactController::contactSitePage($form);

I have this error

PHP Fatal error: Call to a member function getStorage() on null in /var/www/drupal8/core/modules/contact/src/Controller/ContactController.php on line 83

Why I would like to do this in my .theme file ?

Because I have begin to migrate a website in drupal 6 to drupal 8 .(I have try Drupal Upgrate and they works very good ) The page of this website has been built with a little home framework. It call many others not Drupal script. With this, not Drupal Script (Ex:tagada.com/horoscope.php ) and drupal page ( tagada.com/drupalpart/node/10) works with same css and html structure file in a external folder. In Drupal6 the theme worked correctly with a global variable object with node content $node


texts: Results page template of Search API module

texts:
In Drupal 8, the default Search uses template file 'search-result.html.twig' to display results.

I have disabled the default search and enable module 'Search API' and Search API SOLR(used for Backend) to perform search in Drupal 8.

I need to customize the search results page of Search API not default search. How can I do this? The search-result.html.twig template doesn't work, with the Search API module.


texts: What better way to add new features on a project already in production?

texts:
We know that drupal is based on nodes.

I feel it difficult to make updates to a project already in production.

Currently I have two environments. A testing, and other production.
I make changes in the test environment, then I redo the production environment.

Is there any way I can do packages with content types, views, and maybe even taxonomy nodes, and import them into production?

Thank you.


texts: How to get a mini-calendar as a block on sidebar?

texts:
I am using a Event Calendar module to display the Calendar and it is configured using views and linked with the events and popup the event when clicked.

I want a mini-calendar on front page with same events but like a mini calendar.

I have tried creating block for the view but it didn't work.

Can anyone help me how to do that?


texts: Remove/hide title/subject from published comments

texts:
How can the title/subject not be displayed in a published comment.

I have already disabled the subject/title field for entering comments, meaning that users only have a comment body box for which to enter text. (I used the following question and answer to achieve that: Remove subject field from comments )

However, even with this disabled, the initial few words of the comment body get displayed automatically as the subject/title.

Background: I'm developing a stackexchange question/answer style system for my site and am looking for a similar kind of layout.

P.S. I'd be happy with a code-based solution (in a module, or theme) to override a hook (I'm examining the mark-up for clues myself) Or a module would be fine.


texts: Creating Email Sending Rules in WebForm in Drupal 7

texts:
Is it possible to create rules for sending automated emails within WebForm?

Some of the examples include (all emails are separate):-

Send an email to user if he left a field to come back and fill it later.
Send an email if he left certain part of the form.
Send an email if a field is updated (or not updated).

Many Thanks.


texts: Override twig template file from classy theme

texts:
I want to override file-upload-help.html.twig located in core\themes\classy\templates\content-edit. This template displays help text for file upload fields on node edit pages.

If I inspect the file upload help text on a page, above it I see (in debug mode):

BEGIN OUTPUT from 'core/themes/classy/templates/content-edit/file-upload-help.html.twig'

There is no FILE NAME SUGGESTIONS line before or after this line.

My site sub-themes the bootstrap theme.

I tried simply putting a file-upload-help.html.twig file in my sub-theme's templates folder, but it was ignored. Not surprising since I'm sub-theming bootstrap, not classy.

Is there a way to add more information to the theme.info.yml file to override classy templates as well? Or some other way to override the template? If I simply edit the file-upload-help.html.twig file within the classy theme folder, it works, but of course that's bad behavior.


texts: Drupal 7 CKEditor and KCFinder, how to upload to private files directory

texts:
I'm trying to configure KCFinder to upload to the private_files directory that I created outside of the web root. However, it seems like this may not be possible without hacking some library or module files as the KCFinder upload path requires the absolute URL of the website file upload path. I'd rather set this to my private file upload path "/var/www/private_files"
My best guess is that I can hardcode this in /var/www/my_site/sites/all/libraries/kcfinder/core/class/uploader.php but I don't know exactly what to change in this section, or if that will work at all:

// FULL URL
    if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)\/?$/',
            $this->config['uploadURL'], $patt)
    ) {
        list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
        $path = path::normalize($path);
        $this->config['uploadURL'] = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/$path";
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::url2fullPath("/$path");
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";

    // SITE ROOT
    } elseif ($this->config['uploadURL'] == "/") {
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::normalize($_SERVER['DOCUMENT_ROOT']);
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "/{$this->type}";

    // ABSOLUTE & RELATIVE
    } else {
        $this->config['uploadURL'] = (substr($this->config['uploadURL'], 0, 1) === "/")
            ? path::normalize($this->config['uploadURL'])
            : path::rel2abs_url($this->config['uploadURL']);
        $this->config['uploadDir'] = strlen($this->config['uploadDir'])
            ? path::normalize($this->config['uploadDir'])
            : path::url2fullPath($this->config['uploadURL']);
        $this->typeDir = "{$this->config['uploadDir']}/{$this->type}";
        $this->typeURL = "{$this->config['uploadURL']}/{$this->type}";
    }


texts: Is there a standard Drupal way to link to 3rd party configuration forms?

texts:
I am writing a custom module.  On my module's configuration form I would like to provide links to relevant modules' configuration forms; e.g. the cron configuration form.

Is there a standard Drupal way to encode such links?
For instance is there a Drupal function that takes the menu path (eg. 'admin/config/system/cron') and provides an actual URL?

Thanks!


texts: How to show payment form on node form preview in Drupal 7?

texts: I have make a content type, I have make compulsory to preview node before saving, now what I need when user click on the preview button, he can review his information which he wrote in the form and then there should be payment form, if the payment is successful, node will be saved else not.


texts: How can I export Image Crop configuration with an Image Style for custom module?

texts:
I have a custom module I'm re-using on other projects and I want to include an image style with an image crop configuration.

Under the configuration menu, I export a single crop item:

langcode: en
status: true
dependencies: {  }
label: 'Head Shot Crop'
id: head_shot_crop
description: 'Cropping for image head shot.'
aspect_ratio: '1:1'
soft_limit_width: null
soft_limit_height: null
hard_limit_width: null
hard_limit_height: null

I strip out the UUID value for that to be set on new installs.  However, for the image style export:

langcode: en
status: true
dependencies:
  config:
    - crop.type.head_shot_crop
  module:
    - crop
name: head_shot
label: 'Head Shot'
effects:
  ce7f0752-c37c-4ff6-945d-96c298663365:
    uuid: ce7f0752-c37c-4ff6-945d-96c298663365
    id: crop_crop
    weight: 1
    data:
      crop_type: head_shot_crop

I strip out the UUID value as well, but the associated crop configuration seems to be tied to the image style via UUID under the effects key, which also has a UUID value.

How can I pair an image style configuration with a crop configuration configuration so they exist on new module installs?


texts:
Configuring views to display all book-pages inside a book, from whenever you are inside the book.

Is this possible? If so please advice the way to do it.

The contexual filter of All sub nodes of this book page creates an error soon as I relate it to any position or Node ID on a book-hierarchy.
When set view all pages instead - other books page is viewed together with the pages I want to display.

(The  Relationships here is set to top level book with Require this relationship)


texts: How to override -any- of better expose filter?

texts: I am using better expose filter and I need to override -any- from expose and put 'recentpost' here. ANd when page load by default recentpost should be shown and filtered data should be recent posts.


texts: differences between suggesting theme_hook in node and page preprocess function

texts:
I used to suggest the theme hooks in MyTheme_preprocess_page() function in template.php. I mean some thing like this:

$suggest = "page__node__ContentType";
$variables['theme_hook_suggestions'][] = $suggest;

and I was wondering why <?php print render($content['comments']); ?> in the page--node--ContentType.tpl.php doesn't display the comment form. finally I tried suggesting theme hook in the MyTheme_preprocess_node() function and I saw comment form works ! what are differences between suggesting theme hook in these two functions? and which one is preferable?


texts:
I want to export posts with only these data to Excel:

Post title
Post URL
Author
Publish Date

How can I do so?


texts: How to show one page over another in custom way

texts:
I need to show one page over another for non-admin users much like

overlay feature in Drupal7 applicable for admin users. I tried out

overlay module and overlay UI module but not of much help.

All the overlaying pages are custom created and will be invoked on

working page after clicking a link.

Please refer me a solution which should work across all browsers and I

can adjust width and height of overlaying page.I want to implement this

solution for pop up messages, warning and alert also.Please see below

image for reference:

Need your much appreciated help.


texts: Two sort criteria. How to display first those with a specific List (float) selection

texts:
i have a View that provides a list of products(content type Product). This view has two sort criteria. The one is the "SKU" and the second is "New product". The "New product" is a List(float) field and the available options are N/A, Yes and No.

The view must show first the new products and then all the rest. New products are considered those that they have selected the option "Yes".

Is this possible? Any idea?

Thank


texts: Exclude entities currently referenced on a node with entity browser

texts:
I have content type that references a custom entity and uses an entity browser widget to select them.
I want to create a view for the entity browser that excludes entities that have already been selected on the current node so that they're not selected twice.
Not sure if this can be done with default functionality or it needs a custom module


texts: How to make Taxonomy replacement tokens available to the HTML email action in Rules?

texts:
I have created a rule for a client that triggers an HTML email to them every time an authenticated site visitor downloads one of their PDF brochures.

I have no problem including things such as the username, email address, filename and other info, but the client wants to have the "vertical" of the PDF displaying as additional information on the outgoing email.

The PDF's are uploaded as a unique content type and are categorised by using taxonomy terms through a select field.

Unfortunately, when editing the HTML email action element on the rule, there are a whole bunch of replacement tokens, except any related to taxonomy. I tried to "wing it" and create a taxonomy token, but of course this did not work and it seems logical that there would naturally be a disconnect here as how would the rule know to relate the correct term to the file being downloaded.

Any advice with regards to possible workarounds?


texts:
I keep on having different requirements and I always get stuck in Views. This time the requirement is to combine the two columns/fields of a views table but display it in different rows.

The eg: fields I currently have: (Below is the added Picture)

The output of the View in Table (Nickname Multivalue separated by comma)

While Putting the Multiple value field in different rows

In the table settings I did combine two fields like

i.e. Name and Nick Name  but that only gives result like:

(Here Nick Name is displayed after Name)

But the requirements I need to display is: (Name and Nick Name in Separate Row but at the same column). The Column needs to be sortable like normal Views Table Sort function.

Is there any settings in Views which lets me perform this? Or How can I accomplish this ?

Edit: If this is not possible and anybody could guide me to build custom query for this then I'd be very thankful.

Edit 2: SQL Query from Views Log is: (This query outputs the 2nd Image from above)

SELECT node.title AS node_title, node.nid AS nid, field_data_field_nick_names.delta AS field_data_field_nick_names_delta, field_data_field_nick_names.language AS field_data_field_nick_names_language, field_data_field_nick_names.bundle AS field_data_field_nick_names_bundle, field_data_field_nick_names.field_nick_names_value AS field_data_field_nick_names_field_nick_names_value, field_data_field_nick_names.field_nick_names_format AS field_data_field_nick_names_field_nick_names_format, node.created AS node_created, 'node' AS field_data_field_nick_names_node_entity_type, 'node' AS field_data_field_ages_node_entity_type, 'girls:page' AS view_name
FROM
{node} node
LEFT JOIN {field_data_field_nick_names} field_data_field_nick_names ON node.nid = field_data_field_nick_names.entity_id AND (field_data_field_nick_names.entity_type = 'node' AND field_data_field_nick_names.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('girlss')) ))
ORDER BY node_created DESC


texts:
I have inherited a site which had no image management. Instead each image field required you to upload an image instead of reuse an existing one.
I enabled Media Browser and updated to 8.7.
I am also using the following modules [these are the ones I have installed ontop of existing]:

embed
entity_embed
editor_advanced_link
inline_entity_form
entity_browser
media_entity_browser

The problem is every image, either added via an image filed or in CKEditor wysiwyg is now wrapped in a link to the image file:

Twig template: \core\modules\image\templates\image-formatter.html.twig

has the following:

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

But I cannot see where the URL is set in the CMS admin, or how to stop it creating a link to itself. So far I have just copied the template to my theme and removed the url, but I would like to know how to manage this properly.


texts: Resource for understanding Drupal Core functions?

texts:
I'm looking for something to help me understand drupal core and its functions. I've gotten a hang of writing modules, and I've found plenty of resources, such as books and blog posts. But I'm still stumbling when I find I'm needing to manipulate basic core functions such as creating nodes or manipulating users.

Of course, there is the documentation of each function, but it doesn't tell you much beyond what that function does.

For instance, I wanted to create some nodes automatically in my module. I know about node_save, but I didn't know what fields I had to set in order for my new node to be saved properly. The documentation says that node_save saves a node to the database -- so it doesn't tell you anything more than what the function name already says. My node creation in my module is not working. Then I hear somewhere along the about about node_save_prepare for creating new nodes -- maybe I need to do that? But its documentation says that it prepares a node for editing. So I look in my module dev resources, and they talk about the various hooks... which assume some basic understanding of core functionality. So after some more hacking and trial and error, I get my nodes created... with the title only. Do I set the body with $node->body = "blah" or $node->body[0]['und']['value'] = "blah" (and what is all that stuff, anyway)?

Of course I can source dive, but that doesn't really tell you any more about the right way to do things. So I'm looking for something comprehensive about "how do to things". Does there presently exist such a resource?

One book I have read is Pro Drupal 7 Development, and while it's a great resource for understanding hooks, it doesn't go into core functions in a comprehensive, foundational way.

Please note: It's okay to answer "No such single comprehensive resource exists" or "You'll have to piece it together from multiple sources." If that's the reality of the situation, I want to know that rather than continuing my holy grail quest. I'm not looking to be pointed to more piecemeal resources. I'm asking if there's one comprehensive one for understanding core api functions.


texts: How can I create webform preview page where user can go next to submit or edit?

texts: I am trying to figure our what opportunities webform module provides for previewing forms after entering data and editing them by users before submission. I read module code, but did not find anywhere in it even how webform defines its node type. Please help!


texts: What kind of content ends up in the "System help" block? How could I answer this question myself?

texts:
I saw the answer to this question and wanted to enable the "System help" block. When I did, I wondered what other content would be showing on my site besides the "Explanation or submission guidelines" field upon node editing.

Via some grep-ing, I found modules/block/block.module and from what I can tell the block is populated from code there. But it isn't clear to me what would end up in that block. What's the correct "Drupal way" of knowing?


texts: When exporting .sql via phpMyAdmin do you need to include cache tables?

texts:
So I built the D7 site on one server and then moved it to other server and I noticed that .sql size is 8MB in total. I then exported .sql without any cache tables, including cache_* files like cache_block, cache_views and etc. I skipped all tables starting with cache_ and the total .sql size was below 2MB!

So when moving site from one server to other do I need to include cache tables when exporting the .sql or not? Because looks like those cache tables takes 80% of .sql size. And as I understand cache is something temporal?

I came up with this question after moving site to new server and I noticed that tmp folder has 100% copies of images that I uploaded to nodes, but those original images are held in separate files/ folder. So now I got those original images 50MB and copies of those images in tmp/ dir and its also 50MB. So I get extra 50MB taken. I was thinking maybe its because I moved the site with all caches without running cron and etc. and maybe somehow those images in the tmp dir got lost and forgotten by Drupal system or something? I now removed those from tmp dir and it seems to be all working fine.

Strange, can't really understand that.


texts: Editing a single field on a rendered node

texts:
On a given content type called Tracking (which is also a Group), I have a title, OG fields, and a repeating text field called Log. I'd like a member of the OG to be able to enter a value and submit without entering the edit field.

The use case is a mobile site with observers in the field. They won't be editing the entire node. They're just taking notes into a repeating text field?

Is this possible or should I seek a different solution? Or should I just rely on Comments for such a function?


texts: How to upload pdf files and link to them?

texts:
I look for a comfortable solution to upload files (pdf) in drupal 8 and link to them (open the link in a new tab).
The link I like to embed in a paragraph or apply to lists.
Something like entity embed (embedded file). But I do not like the output of this solution.

e.g. I can't open the file new window
e.g. I can't change the title of the link


texts: How to change field value before view sorting

texts:
I've got a view where I have to change the value of a field in certain conditions. I managed to change the value of the field before it's printed but It doesn't affect how the elements are sorted.

In my case, I  use the field price as sorting and my code is:

function real_estast_sub_preprocess_views_view_fields(&$vars) {

  $view = $vars['view'];

  foreach ($view->field as $id => $field) {

    // change the field value depend on result (node id)
    if($vars['view']->name == 'properties'){

        $vars['fields']['field_price_1']->content = "";

        if (isset($_SESSION["pricesfromnodeid"][$vars['row']->nid])){

          $vars['fields']['field_price']->content = "

".$_SESSION["pricesfromnodeid"][$vars['row']->nid]."€
";
          $vars['row']->field_data_field_price_field_price_value = $_SESSION["pricesfromnodeid"][$vars['row']->nid];

        }else{

          $vars['fields']['field_price']->content = "

".$vars['row']->field_data_field_price_field_price_value."€/night
";
        }

      }else{

      }
  }
}

Is it possible to affect the sorting at this point?

  I got the answer for this problem in another question:

  How to sort a view using values not stored in the database>values-not-stored-in-the-database


texts: Programmatically get the continent from ISO2

texts:
I am using the Countries module to assign countries and associated data to nodes. I am currently writing a custom token and only can access the ISO2 data for the value, not the associated data (full name, language, ISO3).

How can programmatically get the other data with only the ISO2?


texts:
I'm trying to make a drupal commerce pricing rule so that if the customer has 14 items in their cart they'll get 10% off their order. Here's what I tried:

{ "rules_overall_discount" : {
    "LABEL" : "Volume Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "php",
      "inline_conditions",
      "commerce_line_item",
      "commerce_product_reference"
    ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_order_has_specific_quantity_products" : {
          "commerce_order" : [ "site:current-cart-order" ],
          "products" : "\u003C? $commerce_line_item ?\u003E",
          "operator" : "\u003C",
          "quantity" : "14"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : ".9",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}

I think the:

"products" : "\u003C? $commerce_line_item ?\u003E",

might be the problem. It's asking for SKU's but I simply want it to apply to everything.


texts: Is it possible that these modules conflict with each other?

texts: I have a view set up with the format Views Accordion. I have installed the module draggable views so that I can order each node as I like whenever I add a new node to the view. I'm finding that the sort version of this view display isn't rendering the drag and drop anchors at all. Is it possible that there is a conflict between Views Accordion and Draggable Views?


texts: Problem to display name from current logged

texts:
I've created a custom block to display info from current user. When i'm logged with username "David", i see on my custom block the username from my last login with other user account.

I have to clear the cache to see the correct username from current user logged.

See here my code :

    class UserProfilBlock extends BlockBase {

  public function build() {

    $userinfo = [];

    $account = \Drupal::currentUser();
    $uid = \Drupal::currentUser()->id();

    $user = \Drupal\user\Entity\User::load($uid);

    $userinfo['name'] = $user->get('name')->value;

    return [
      '#username' => ucfirst($userinfo['name']),
      '#theme' => 'user_info_block',
    ];

  }

  public function blockForm($form, FormStateInterface $form_state) {
    $config = $this->getConfiguration();

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['userprofilinfo_settings'] = $form_state->getValue('userprofilinfo_settings');
  }
}

Something is wrong on my custom module ?


texts: Passing an argument to a node causes 404

texts:
On my page I have a block that reads a variable in the URL.  The page that it reads it on is a node.  When I pass an argument through the URL to the node, it causes a 404 error. ex:

www.example.com/experience //This is the node, it works
www.example.com/experience/asia //Asia is the argument, I get 404

I've tried configuring the URL Alias to "experience/*", but this obviously didn't work and only accepts '*' as the argument.  What do I need to configure to make this work?

I've heard of some modules that automatically add the aliases to the configuration table, but I would prefer a more straight-forward solution.


texts: Show required user profile fields after the account is verified during first login

texts:
The user can register with their username, email and password. Once the account verifies their account i need to show custom required fields like age, sex , profession to be filled.

Complete profile comes in handy to force filling of required fields.

But, if i mark the fields as required they show on the registration form. Is there a way to hide the required fields of the user profile in the registration form???

I tried Field Permission and removed permission for anonymous users to see the fields. Though it doesn't show the fields, once the form is submitted it returns the hidden fields as required.


texts: How to make nice content manager approval page?

texts:
The client wants to allow users to upload files but only publish the ones that are approved by the content managers. The content managers want a nice way to flip through pictures and quickly accept or reject pictures.

I created a view where someone can flip through unpublished pictures.

Is there a way to add a check box that corresponds to the the published checkbox in the add content? Basically be able to edit the content within this simple view, but all they would need to edit is published/unpublished.

Any Ideas. Hopefully there is a way to do this without another module, but I'm not picky at this point.


texts:
I'm trying to place "Add new item" button before the unlimited values field. Also two buttons un top and below field will work. In custom module added new button but it brakes AJAX call for both buttons. This is needed for Field collection field but I doubt it matters. This is how I've tried to build second button:

    $form['field_fieldname']['add_more2'] = array(
    '#type' => 'submit',
    '#name' => 'field_fieldname_add_more',
    '#value' => t('Add another item'),
    '#submit' => array('field_add_more_submit'),
    '#ajax' => array('callback'=>'field_add_more_js','wrapper'=>'field-fieldname-add-more-wrapper','effect'=>'fade',),
    '#limit_validation_errors' => array(array('field_fieldname','und')),
    '#attributes' => array('class'=>array('field-add-more-submit'))
  );


texts:
In my shop site, on each of the products listed can we please just list the dollar amount i.e. $80.00(for eg.) - and remove the default currency(eg. AUD) and (GST (exc) )text that follows?
How to formatting the price?


texts: Content:author Relationship Not Showing Fields for Comments View

texts:
I have created a view to show a nodes comments in a block.

Authors on my site have different roles, and they can create a single business page. On that page, other users can leave comments.

For site authors that have a "Free Listing" role, I want to hide the ability for other users to post comments.

To do this, I have added a view to display comments, then added a relationship for Comment:Content, then a relationship for Content:Author.

In my previous experience, this should give me a field (Content)Author:Role to filter results by. Instead, I get no additional fields, just the standard Content:Author ID field, which then tells me..."If you need more fields than the uid add the content: author relationship", I have!!!

Have I uncovered a bug? Or am I missing something?

Any advice appreciated.


texts: Some nodes served headless Drupal and some nodes served with Drupal

texts:
We are building a site that will be built and served via Drupal.  We want to have microsites that we want to share SOME of the content between the main site and the microsite.  We are thinking to build the microsites via Headless Drupal and use API from the main site.

The problems I see:

For example, node/2 should only be accessible on the microsite.  How would the main site which is not headless know that it can't access node/2?  Basically, some nodes will be served headless and some will be regular Drupal.

Would it make things easier to just have the main site be headless as well?


texts: Allowing file-transfer to use sftp or ssh?

texts:
I have my own dev-server that I installed with Ubuntu 11.04. When I set it up, I was fairly new to the whole "server thing", so I'm not sure that I set up everything 100% up to industry standards.

The problem I am having, is that trying to automatically update things almost never works when using drupal's UI.

I usually got around this, by just ssh-ing into my server, and using drush to update everything.

The problem now, however, is, that instead of updating the site, I am trying to install "apps" (not modules), and I am not sure how to do this with drush. (plus I want to figure out how to fix this FTP problem anyway)

What usually happens, is that I will get an error (not a specific one, just one that is saying Error installing nameofmodule)

Recently though, I tried using a different user account with direct access to the folder (it being the user's home folder), and I am getting the folowing error

Warning: ftp_login(): Login incorrect. in FileTransferFTPExtension->connect() (line 59 of ..../includes/filetransfer/ftp.inc).
Failed to connect to the server. The server reports the following message:
Cannot log in to FTP server. Check username and password

I know the username and password are correct, I checked them more than a dozen times in terminal, however, I realized, that whenever I ftp into the server, I get an error if I use ftp, but I instead have to use sftp.

Is that what my problem is? If it is, how can I get Drupal to use sftp or ssh to transfer files instead of just ftp?

PS. If it helps, I am using the OpenEnterprise 7.x-1.x-dev distribution of Drupal


texts: Invoking the rate module in views template file doesn't work

texts:
I have installed both the Views and Rate modules. In the views-view-fields.tpl.php file, I put the following code.

$node = node_load($row->nid);
echo $node->content['rate_poll']['#value'];
echo $node->title;

There is no output for $node->content['rate_poll']['#value'], while the code outputs the node title. Why?

How can I output $node->content['rate_poll']['#value'] in views-view-fields.tpl.php, or other Views files?


texts: How to include pages created with Views in a Search API index

texts: I have configured Search API on a site to search all content. It works fine. The only thing I can't work out is how to include pages which are views in the search index. Is the only way to do this to convert the page to a block, and then create a page containing that block?


texts: using hook_form_FORM_ID_alter with #states

texts:
I am trying to use checkboxes to display inline entity form elements only when the boxes are checked. However, my code doesn't seem to be working. It will hide the element, but when I toggle the checkbox, it won't display what was hidden.

Here is my code:

function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und'] = array(
        '#states' => array(
            'visible' => array(
                ':input[name="field_affiliation_type[und][#options]"]' => array('value' => 'Nonprofit'),
            ),
        ),
    );
}

Here is a screenshot of the field_your_nonprofit_connections field:

And here is one for the field_affiliation_type field:

Based on what I have been reading in this related question (When using hook_form_alter to modify a content type's node add / edit form, where do I put the #states property?),
I have now realized that my form is not even including the #states element at all.

How do I add the #states element into an already existing form via
hook_form_alter?
And, how do I get the checkbox field to toggle the visibility?


texts: How do I format a date value for a 3-column date drop-down widget?

texts:
I would like to pass a date in the format 2013-04-23 00:00:00 as a #default_value into a form builder function:

$form['date'] = array(
    '#title' => t('Date'),
    '#type' => 'date',
    '#default_value' => $my-array['date'],
);

...but the form renders dates in a three column drop-down widget (which I want to keep). How do I reformat my date and/or form builder function so that my three drop-downs display 23 Apr 2013? At present, they display 02 Feb 1900.

Thanks

Solution

See @tostinni's answer for half of the soluion. This is the second half:

$timestamp = strtotime($my-array['date']);
$day = date('d', $timestamp);
$month = date('n', $timestamp);
$year =  date('Y', $timestamp);


texts: How to set up salt hash while installing Drupal 7?

texts:
I am no expert in salt hash but while I was installing Acquia Dev, I noticed a variable $drupal_hash_salt, filled with a randomly generated string, in settings.php of newly installed Drupal 7 and a file called .hashlist under root drupal installation folder. Can someone help me understand the salting concepts in Drupal 7?

When I tried to import a new version of Drupal 7 site, I could not see any random string in that same variable and also no .hashlist file. I may be doing something wrong here. I tried googling around to see if I could find something useful but no luck.

So I have 3 questions

How to do salt hashing in Drupal 7 during/before installation process?
What kinds of data are being hashed (other than password)?
How can I extend this salting concept further?

Thanks a lot in advance.


texts:
drupal_mail() is formatting my email body.
Before: http://pastebin.com/LbBy04BZ (note 1 line)
After: http://pastebin.com/nEx7AFwU (note multiple lines)

It should not, because Line 23 in /modules/system/system.mail.inc is the following one:

$message['body'] = implode("\n\n", $message['body']);

How can I prevent the reformatting of my mail content?


texts: Link field sanitizes query string from foo.cgi?123456 to foo.cgi?0=

texts:
On my Drupal 8 site I have a custom content type that contains, among other fields, a link field. When I create a node and add the following external URL as one of the values of the link field:

http://www.isfdb.org/cgi-bin/title.cgi?1580

the rendered page contains this mangled query string:

http://www.isfdb.org/cgi-bin/title.cgi?0=

Is this the result of some misconfiguration on my part? How can I get the rendered page to use the correct URL?

I should probably mention that the D8 site is the result of a migration from a D7 site. On the old D7 site, the same URL was rendered correctly. The new Drupal 8 site uses Drupal version 8.6.1.


texts:
I would really like to:

to create a paginated table of nodes, displaying only those that the user has 'update' permission to; displaying title, content type, and path alias
the path for nodes may be different depending on the content type. More specifically, I have created a content type 'file' to wrap an uploaded file; I would like to display the url alias associated to the actual file, rather than the url alias of node that wraps it.

There are a few approaches that I have considered,

Creating views. However, the above behavior seems to require merging two views --- one for nodes of type file, one for node of content type not equal to file. I have no idea how to merge two views. Also, this method seems to create a dependency of the output of the view on the content type 'file'.
Use database query + pagination. In many of the examples that I have seen, if I want to add pagination to a table, I can do the following (see this very excellent tutorial):

run a database query using either pager_query or the extend method for the SelectQuery object
theme the query results, and use theme to generate the pager based on the query

The problem with this approach is making theme('pager') play well with filtering the database entries by node_access. For example, for an user with relatively few nodes that she can edit, the table displays many empty pages.
Database query, filter into array, then use pagination on array as suggested by this post. This does get the table to work correctly. However, it is really expensive, because the entire query is run at this point, and the pager is purely for aesthetic purposes; seems a bit wasteful.

Now (thank you for bearing with me so far), is there a some way to create this table this without using views, but faster than method 3? I can also accept 'no' for an answer; in this case, it would be nice to know why not.


texts: D8 Install/uninstall custom module - 'field_storage_config' entity with ID already exists

texts:
I created a custom module which essentially is a replica of the Article CT .yml files which come with the D8 standard install-profile.

When I installed the custom module, it successfully created everything i expected it too. I then disabled it, then re-enabled and the module will not re-install giving the following error:

  Drupal\Core\Entity\EntityStorageException: 'field_storage_config'
  entity with ID 'node.custom_field' already exists.

I originally solved this issue by declaring the module as a Enforced dependency on the node.type.yml

langcode: en
status: true
dependencies:
   module:
    - menu_ui
   enforced:
     module:
       - custom_module

This worked for the body field and allowed me to enable/disable the module without getting the duplicate ID error. but as soon as i added the image field the ID is a duplicate and I cannot re-enable the module. The id is unique, and module will enable if i change the ID prior to enabling, but thats unacceptable.

  EDIT: appears after removing the image field from the CT, the body
  field now is now being affected by the same error. So enforcing the
  module doesnt work.

I would assume this is because it is inside of the config/install folder, but there are no examples on custom modules that install content types when installed. at least I cannot find any at the moment.

My question would be: What is the proper way to add content types when enabling a custom module?

how to avoid the duplicate ID error when installing content types when disabling/enabling the custom module?


texts: Drupal and jQuery Plugins (ie tools) - overlay - mask isn't working - suspect javascript issue

texts:
G'day all,

I've implemented the demo available at http://flowplayer.org/tools/demos/overlay/modal-dialog.html in a hook_menu to test (note that this is the jquery tools plugin, available via the module jquery plugins). Everything works fine with the exception of the mask, I cannot get it to work.

The only difference between the example javascript on the above link and what I'm using is that I had to encapsulate the javascript with the following:

(function($){
  $(document).ready(function() {
    <demo javascript code goes here>
  });
})(jQuery);

The demo code appears to be using:

var triggers = $(".modalInput").overlay({
  // some mask tweaks suitable for modal dialogs
  mask: {
    color: '#ebecff',
    loadSpeed: 200,
    opacity: 0.9
  },
  closeOnClick: false
});

Which all makes sense to me and I cannot see why it wouldn't work.

My version of the javascript is (I removed one button): http://pastebin.com/MH6ehmTR
My version of the html is: http://pastebin.com/aW6UpFBQ
My version of the css is: http://pastebin.com/tUQWDqZp

The html is taken from the generated html by drupal.

The reason why I need this fixed is to disable access to the rest of the page while the dialog box is open (thus becoming modal). The current situation is that a person can interact with the rest of the page while the dialog is open.

FYI the browser is firefox, it works for the demo code, just not for the drupal implemented one. Also the method of getting jQuery tools overlay available is via the jQuery plugins module.


texts: Webform 8.x-5.0-RC3 can't set custom settings

texts:
Here is my problem. I have a drupal website I'm working on where I've got webform with custom settings (such as checklist with custom elements and some others). I was on 5.0-beta24 and everything was fine. I saw that an update to the RC3 was available so I tried to see if there was any breaking change. And it seems that my custom settings are no longer saved.

What is the breaking change, and is there a solution so I can still define my custom settings / another way to do it ?

You can find below my current function to alter the settings form and add my custom's one.

<?php
function mymodule__form_webform_settings_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $settings = $form_state->getFormObject()->getEntity()->getSettings();

  $form['general_settings']['description']['#title'] = t("Subtitle");
  $form['general_settings']['description']['#type'] = 'textfield';

  $form['form_settings_categories'] = [
    '#type' => 'details',
    '#title' => 'Catégories',
    '#open' => TRUE,
    '#input' => FALSE,
  ];

  $form['form_settings_categories']['categories'] = [
    '#type' => 'checkboxes',
    '#options' => \Drupal\avantages\Services\PopulationsService::getPopulationList(),
    '#title' => t('Catégories'),
    '#default_value' => $settings['categories'] ?? ['test'],
    '#required' => FALSE,
  ];

}

Edit :

After some research, it seems (but I can be wrong) that the line that cause trouble is this one

  /**
   * {@inheritdoc}
   */
  public function setSettings(array $settings) {
    // Always apply the default settings.
    $this->settings += static::getDefaultSettings();
    // Now apply new settings.
    foreach ($settings as $name => $value) {
    if (array_key_exists($name, $this->settings)) {
      $this->settings[$name] = $value;
    }
  }

  return $this;
}

As my custom setting is not is getDefaultSettings, I can't save it.

Is there any new way to save custom settings ?

Thanks


texts:
I am using HTMLMailSystem to send emails from my Drupal 7 website. The problem is that random spaces appear in long emails. I have read about this and I tried the solutions on PHP mail function randomly adds a space to message text.

I added the following code in my module's hook_mail_alter(), but it didn't help.

$message['body'][0] = chunk_split(base64_encode($message['body'][0]));
$message['headers']['Content-Transfer-Encoding'] = 'base64';

I also tried using wordwrap(), and spaces are gone, but result is pretty ugly.

How can I fix this issue?

I am also using the Mailmime module, if that is relevant.


texts:
I am building a theme for Drupal 8 that I want to make available in the drupal.org theme section. As such, I want it to conform to best practice code wise. When adding JavaScript, I notice there has been some changes. Here is how I do it:

function THEMENAME_preprocess_page (&$vars, $hook) {
  $path = drupal_get_path ('theme', 'THEMENAME');
  // Render the main scripts file.
  $local_js = array (
    '#attached' => array (
      'js' => array (
        $path . '/js/THEMENAME.js' => array ('group' => JS_THEME, 'weight' => 9999),
        '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js' => array ('group' => JS_THEME, 'weight' => 9000),
      ),
    ),
  );
  drupal_render ($local_js);
}

Is this it? the best-practice way?

Edit:

In accordance to Aneek's answer I am now including JavaScript this way:

First, I created a THEMENAME.libraries.yml:

THEMENAME-base:
  version: 1.0
  js:
    //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js: {}
    js/THEMENAME.js: {}

Then, in THEMENAME.info.yml I added the libraries:

--snip--
core: 8.x
stylesheets:
  all:
    - css/grid.css
    - css/style.css
regions:
  header: 'Header image'
  home_intro: 'Home intro'
  breadcrumbs: Breadcrumbs
  content: Content
  sidebar-main: 'Sidebar main'
libraries:
  - THEMENAME/THEMENAME-base

This method includes the JavaScript files to all pages on the site. If one needs to include on specific pages only, the preprocess_page would probably be the way to do it.


texts: How to use entity form in pop-up window?

texts:
I have created a view, and there is one column named "forward to delete". I want to open an entity form in a pop-up after clicking on this link and get the node id of the clicked node so that I can use this node id for other purpose.

I am using the entity form module.


texts: how to add custom css as default for the whole site

texts:
How can I add my css file as default for the whole Drupal site?

Where to put my CSS file so that it applies to whole Drupal 7 site that I am creating.


texts: I have made changes to a Feature on a Drupal 7 site.  I want the same feature to be updated in another website. How to do it using the drush features-update command? When I run it, it asks to overwrite the previous Feature, but nothing new comes in the Feature.


texts:
I have the following URL aliases for the same node.

/products/single-room/product-listing/wall-mount
/products/multi-room/product-listing/wall-mount

I have two details button Single & Multi-rooms; Single Room button has a link to /products/single-room/product-listing/wall-mount and Multi Room button has a link to /products/multi-room/product-listing/wall-mount. When I click on Single Room or Multi Room Button, both will redirect to /products/multi-room/product-listing/wall-mount; when I delete the multi-room alias the single-room button will go to /products/single-room/product-listing/wall-mount which is correct but multi-room will give the 404 not found error.

What I need is to have two aliases for same node: When users click on single, they are redirect to the same node with /products/single-room/product-listing/wall-mount as URL; when users click on multi-room, they get redirected to the same node with /products/multi-room/product-listing/wall-mount as URL.

Please help me out?


texts: What is the best way/api to load a node by node content type and a field value?

texts:
Aside from plain SQL, is there any Drupal api to retrive node(s) by passing a node CCK type and a field value?

For example, I would like to get the node which is an Assignment CCK type, by matching an integer CCK field Assignment Score value >= 65.

In PHP.


texts: "Page cache maximum age" is set to "no caching" but the block seems to be cached

texts:
I have a Drupal 8 standard installation on Azure. I wrote a block that uses PHP to load external content; I added a timestamp to the block as well. Under Page cache maximum age, the site is set to no caching. When I refresh the page, the timestamp doesn't update telling me it's not attempting to reload. If I manually clear the cache, all is good and the timestamp updates.

Why would this be?

As I mentioned before, these blocks are loading external content. Ideally I could set it so that these blocks alone wouldn't be cached. Is this possible?


texts:
How can I retain the current user's search in the search block input? Please don't suggest a third party module for this unless strictly necessary. I'm also aware of views exposed filter and that's not what I want.

Currently, I managed to grab the query with this code:

if($form_id = 'search_block_form'){
  $keys = \Drupal::request()->query->get('keys');
  $form['keys']['#attributes']['value'] = $keys;
}

The issue is that the value doesn't update for new searches, I think it may be cached. So I have a few questions...

How can I update it from the URL and not the cache?

How to grab it only if the current page is /search/node?

Is it safe or can it be susceptible to SQL injections if someone directly edit the URL in the browser's address bar and press enter/return?


texts: The following module is missing from the file system: "post_articles"

texts:
I was given a Drupal website in the form of a Drupal database running on a website and an archive containing a Drupal installation complete with a theme. Upon uploading the installation to the server and pointing it to the database, Drupal showed me a list of missing modules errors. I have installed the modules manually, except for a "post_articles" module. I have not been able to find that module anywhere and am at loss. Here is the complete error:

User warning: The following module is missing from the file system:
post_articles.
For information about how to fix this, see the documentation page. in _drupal_trigger_error_with_delayed_logging() (line 1156 of drupal\includes\bootstrap.inc)

The website itself is unusable. I hope it is due to the missing module but not sure.


texts: what function do i use to print out a menu? the menu was created in the admin

texts:
i have node that i simply want to display a menu. the menu itself is a list of archived articles, and was created in the admin.

i know how customize the node to do so, page--node--11.tpl.php.

i deleted the print render $content. so now, my pseudo code would look like.

print $archive_menu;

or perhaps i need to call a function? can someone explain how to do this?

thanks