texts: How to implement a cancel button with required elements

texts:
I have a form in which I have added a cancel button which looks like this:

$form['cancel_button'] = array(
  '#type' => 'submit',
  '#value' => t('Cancel'),
  '#name' => 'cancel',
  '#access' => TRUE,
  '#submit' => array('mymodule_cancel'),
  '#limit_validation_errors' => array(),
);

This form has required elements in it as well and what is causing the problem. I thought that by having the #limit_validation_errors statement would prevent the required elements check, but that is not happening. How do I prevent the required elements from being checked?

EDIT: I found this answer on a different question Isn't it possible to have multiple buttons  along with a submit button?

This would explain the behaviour I am seeing but it seems to contradict the Drupal documentation about limiting error checking. This would really screw up people who want to save a draft of a form that has required fields. I am pretty sure I have seen this done before, so there must be away around this.


texts: I saved a cache entry using cache_set(). How can I clear this entry using Drush?


texts:
I know you can enable Web services for content in Drupal8. You also need to set permissions to make a GET request to content.

But I was wondering if it's possible to set for each node if it can be accessed by GET request or NOT. How can I do this? Because now they can access all nodes ... .


texts: Is it possible to create a hierarchical exposed filter in views using the Data module?

texts:
I'm using Data module to adopt tables from the same DB as 'native' Drupal tables and Views module to present the data.

I added two dropdown exposed filters with Selective filter module. It takes all values from fields and puts them to the selective list. It works fine.

However I would like to configure my exposed filters the way that the second filter will show values according to the chosen value in the first one. E.g. if you choose a specific academic department in the first filter, the second one will offer you the list of this department's staff members.

Is it possible to achieve such a behavior? If so, do I need any extra modules (taxonomy?) or should I create a module myself?


texts: views preview is different from actual view

texts:
The preview of my view looks exactly how I want it to but unfortunately is different when I go to the actual page. Anyway to fix this?

This is using Drupal 8


texts: Constraint handling for @DataType (Typed Data API)

texts:
I am creating a new data type, 'duration'. The value will be a duration string that is used by a DateIntervale object.

The value is a string, but with a specified format. I'm assuming that due to it being a string, for my @DataType I should either extend StringData, or PrimitiveData. And I would like to add required validation to this data to ensure that the value contained is in the correct format.

I've been reading through documentation, and reverse engineering other @DataType objects, but I've not been able to find what I'm looking for. So what I want to specifically ask:

Should I extend StringData, or is it better to extend PrimitiveData?
How/where can I add a constraint onto this data. By this I mean, what method should I use to ensure that when someone calls setValue() using this data, the string can be validated using a regex to ensure it's the proper format.
If the value is not the proper format, how is this handled? Is there a way to call an error? Should I throw an Exception? Or should I set a default value instead of the value that was supposed to be submitted?
Am I looking at this the right way?

Thank you.


texts: Drupal 7 Views: Use one views.tpl.php file for multiple views

texts:
Views allows you to customize output with tpl.php files.

My theme directory is getting overloaded with the .tpl.php files! Many of the files repeat the same content.

I would like to use the same tpl.php file for multiple Views. How can I do this?

Ideally, I would like to call a template file when a tag has been applied to a View.

Steps I have Tried

Use Multiple Views displays:
 This thread suggests putting all the Views that use the same template file into one view and then creating separate Views displays for them.

This isn't practical for my situation, as my Views have very different fields, which would result in a lot of overriding (which makes them harder to manage).

Views Pre Process
This article suggests to use a Pre Process function. You can then select specific views and use a theme hook suggestion to load template files. However, the code it provides is incomplete, so it's not clear how to load the template files. It's also not clear how to load different field/row/display/style templates for a single view (as a View template can take one of a field, row, display or style template).


texts: How can I set a response URL to use https?

texts:
I have a json response that I need to force to use https when on the live server.
So I need to detect if the response URL is using http or https.
If it's using http I need to switch it to https.

How can I force the header to use https?


texts: Hook_Form_Alter Edit Existing Field Type

texts:
I am using hook_form_alter in template.php to add datepicker to a field on an exposed view filter.

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

  if($form_id == "views_exposed_form"){
    $form['data_2_op'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}

But all it is doing is adding another field into the form, rather than editing the field I have declared. Is there a way I can just add #type > 'date_popup' to an existing field?

EDIT:

Results after using...

drupal_set_message($form_id);  // print form ID to messages
  drupal_set_message(print_r($form, TRUE));  // print array to messages

views_exposed_form
Array (
  [#info] => Array (
    [filter-combine] => Array (
      [operator] => combine_op
      [value] => combine
      [label] => Search Event ID
      [description] =>
    )
[filter-data_2] => Array (
  [operator] => data_2_op
  [value] => data_2
  [label] => Choose Date [description] =>
  )
[filter-data] => Array (
  [value] => data
  [label] => Data field
  [description] => )
  [filter-data_1] => Array (
    [value] => data_1
    [label] => Data field
    [description] =>
    )
  )
[combine] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )
[data_2] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )


texts: Best bet for elastic search using search api

texts:
I am using elastic search with search_api module. I found https://www.drupal.org/project/search_api_best_bets module which seems to work only with solr instance. Is there other way to do best bets using elastic search or is there any way I can create my own Query Handler extension for elastic search. Have anyone worked already on this? Please suggest.

Thanks,

CIsSharp


texts:
I want to integrate infolink code. Finally I copied this code just before print $closure in page.tpl.php file at the bottom to make it work:

<script type="text/javascript">
   var infolink_pid = 326015;
   var infolink_wsid = 3;
</script>
<script type="text/javascript" src="http://resources.infolinks.com/js/infolinks_main.js"></script>

But why this code does not work when placed in the same place?

<?php
global $theme;
$js_fl_path=drupal_get_path('theme',$theme).'/infolink.js';

drupal_add_js($js_fl_path, 'theme', 'footer');
?>

I'm using a subthemed Garland in sites/all/themes/ui_garland.


texts: Calculate the sum of two form fields with javascript?

texts:
Hello there i was wondering if anyone had the solution to a problem i am having with my  Custom Module. I created a custom form a few days ago and i need two or more(4) field values to be added together and the sum to be output in another field(total).Please not i am using form_panels here s snippet of how the fields are built.

$form['Contract']['twelfth'] = array(
 '#type' => 'textfield',
 '#title' => t('Plus FEE of:'),
 '#size' => 40,
 '#field_prefix' => "$",
 '#form_panel_row' => 7,
 '#form_panel_col' => 1
);
$form['Contract']['thirteenth'] = array(
 '#type' => 'textfield',
 '#title' => t('For a OTHER PRICE of:'),
 '#size' => 30,
 '#field_prefix' => "$",
 '#form_panel_row' => 7,
 '#form_panel_col' => 3
);
$form['Contract']['fourteenth'] = array(
 '#type' => 'textfield',
 '#title' => t('For a TOTAL PRICE of:'),
 '#size' => 40,
 '#default_value' => "",
 '#field_prefix' => "$",
 '#form_panel_row' => 8,
 '#form_panel_col' => 1
 );

now how can i insert Jquery or Javascipt into this form to calculate those two fields together?


texts: I want to know what sliders are available for Drupal 7, and which ones can be used in blocks.


texts: Is it possible to add css class to the page's body tag with rules when certain conditions are met?

texts: I seem to have read that there is a way of making Rules add a css class to the body tag, but I can't find out how to do it. Any ideas?


texts: How to hide some administer option from all users?

texts:
I want to hide some administer options (such us: Actions, File system, etc) from all users, including admin (user='1').

How can I do that?

Thanks


texts:
I'm trying to get Drupal 6 to automatically add a taxonomy term in a migration. Basically I have

// Some code
$this->addFieldMapping('field_supplier', 'source_supplier');

In this case, field_supplier is a taxonomy term. What I would like to achieve is for Drupal to check if the value in "source_supplier" is an already existing term, and in that case use that, otherwise it should create a new one and use that.
I tried using

$this->addFieldMapping('field_supplier:create_term', 'source_supplier');

and

$this->addFieldMapping('field_supplier', 'source_supplier')->arguments(array('create_term' => true));

But it didn't work. Any ideas? Thanks!


texts: Selecting from a column in a joined table in Views

texts:
I've got two tables: {students} and {student_names}. Students is the base table, with a primary key of {students}.sid. Student names is the joined table, and has a key of {student_names}.sid.

I've defined my join in hook_views_data:

$data['students']['table']['join']['student_names'] = [
  'left_field' => 'sid',
  'field' => 'sid',
];

I want to select the given name of the student from the joined table. I've defined the field as follows (again in hook_views_data()):

$data['students']['given_name'] = [
  'title' => t('Given name'),
  'help' => t('The given (first) name of the student'),
  'field' => [
    'handler' => 'views_handler_field',
 　　'click sortable' => TRUE,
  ],
  'sort' => [
    'handler' => 'views_handler_sort',
  ],
  'filter' => [
    'handler' => 'views_handler_filter_string',
  ],
  'relationship' => [
    'base' => 'student_names',
    'field' => 'sid',
    'handler' => 'views_handler_relationship',
  ],
];

I'm getting this error:

  Column not found: 1054 Unknown column 'students.given_name' in 'field list'

How can I tell views that the column is in the {student_names} table and not the {students} table?


texts:
I have created a view of type service that fetches Taxonomy terms, response as following :

{
  data: [
    {
      taxonomy_term_data_name: "Child Term",
      tid: "6",
      parent_id: "37",
      order: "0"
    },
    {
      taxonomy_term_data_name: "Parent Term",
      tid: "37",
      order: "0"
    }
  ]
}

the taxonomy has parent/child in it, as the response show, I get the parent_id in the response for childrens but not for parent terms, is there any change that I can set the parent_id to 0 for parent terms ?

I have to mention that I am a Java developer, and new to Drupal.


texts: Creating a view with multiple latest content types

texts:
I am looking to create a view for my home page that displays the 3 last added items for 2 different content types (articles and news). Like 2 lists next to each other that also has the option to show more.

I already tried by creating a view with one of the 2 content types but I couldn't seem to manage to show both content types in the same view.


texts: Configuration of views with entity reference fields

texts:
I've read several guides about this subject but still incapable of achieving what I want.

I have a main content type (aventuras) and then another content type for images. The images are referenced to the main content type via an Entity Reference field.

I want to create a view that shows a list of all the nodes of the main content type (their titles and other fields) along with their images (reference field).

I think I need to add the "Entity Reference: Referenced Entity" relationship and then the image field with that relationship selected, but that is not working (it only shows fields of the main content type, no image).

I've tried several alternatives (contextual filters, adding also the relationship to the filter, using Referencing Entity instead of Referenced...) without any luck.

Maybe this is an annoying noobie question that has been answered before, but I've searched and tried a lot and I can't find the solution for my case.

Any clue would be much appreciated. Thanks!


texts:
I am trying to do a simple CSV import into a node using the Drupal Migrate module. I have created the .module and .info files and double-checked them against several examples online. I have also created a .inc file including

class CrfmMigration extends Migration

I have enabled my module from the Modules Administration panel and there are no errors. However, when I go to the Migration UI, my migration class isn't listed at all. The Beer and Wine samples show up just fine, but my custom migrate class is nowhere to be found. I'm not even sure which file the problem could lie in. I am more than happy to provide any additional information as necessary to figure this out. I prefer not to use Drush if possible, but I will if there is no other option.


texts: How to run custom function after clicking next on a multi page webform

texts:
I've created a multi page webform and I want to run a function after the user clicks the 'Next page' button on the first page only. After the user fills in the data on the first page, I want to grab that data and do stuff with it. After that the webform should work like normal on through the submission process.

How can I do this so that the function runs only once? I've tried using hook_form_alter and testing the value of $form['details']['page_num']['#value']. This value is 2 if I'm on the second page. For some reason the function fires twice and I can't figure out why.

Thanks


texts: How do I create a list with the previous and next referenced entities of the one being viewed?

texts:
I have 2 content types: Books and Chapters.

Books have an entity reference field that can accept unlimited values.
Chapters have an entity reference field (single value) that corresponds to a book.

These entity reference fields are "linked" with the Corresponding Entity References module.

My goal is to create a block that will be displayed at the top of the Chapter nodes that will act like a pager of some sort and will display the previous and next chapters from the one that is being viewed.

For example, when someone views Chapter 1 of a book, the block will show:

Chapter 1 (no link)
Chapter 2 (link to Chapter 2)
Chapter 3 (link to Chapter 3)
Chapter 4 (link to Chapter 4)
Chapter 5 (link to Chapter 5)

When someone is viewing Chapter 10, the block will show:

Chapter 8 (link to Chapter 8)
Chapter 9 (link to Chapter 9)
Chapter 10 (no link)
Chapter 11 (link to Chapter 11)
Chapter 12 (link to Chapter 12)

and when someone is viewing the last chapter (say chapter 25):

Chapter 21 (link to Chapter 21)
Chapter 22 (link to Chapter 22)
Chapter 23 (link to Chapter 23)
Chapter 24 (link to Chapter 24)
Chapter 25 (no link)

My immediate thought was to create a view, but after I have created the view with the proper contextual filter and relationship, there was no option to sort the results based on the weight of the Chapter in the Book's entity reference listing.

I then tried to use Views PHP and sort the results via PHP with code like that:

$node = node_load($row1->nid);
$weights = $node->field_book_contained_chapter['und'];
array_walk($weights, function (&$v, $k) { $v = array_shift($v); });
return array_search($row1->nid_1, $weights) - array_search($row2->nid_1, $weights);

which works fine only if you select to display all items (doesn't work with pagers) but is also very inefficient: it runs through the whole array of referenced entities for every comparison between two rows (and some of my books have more than 1300 chapters). I haven't tested how it performs but my gut tells me that it's not a very elegant solution (I will also have to do additional filtering after I sort them).

Now I'm thinking about creating a custom block with php code that will traverse the $node->filed_book_contained_chapter['und'] array and find the neighboring articles of the current article. This seems like a more efficient solution than the views' one, but still feels kind of an awkward approach.

Is there an obvious way that I'm missing to achieve the functionality that I'm after?


texts:
In a screencast based on Drupal 6, I spotted (~3:45) that several fields had an additional "create and reference" icon that would pop a secondary dialog, for in-place creation of non-existent nodes, which would then be added as reference. This appears to be missing from Drupal 7 Reference module, which is now responsible for fields of that type, and I can't seem to find any evidence it's going to be put back.

My homework:
I dug up an old groups.drupal thread where eventually someone posted a round-up of many options last year, but most of those now range from inactive to abandoned. A few have issue threads full of people asking about a Drupal 7 upgrade, with absolute silence from the maintainers.
From that list, two actually show Drupal 7 work:

Node Reference Create: Seems to only do the barest minimum: create a node with a title of what you input in the textarea. To provide values for any other fields, you need to make your way over to that node's individual edit screen. This isn't enough for my needs.
Corresponding node references: I'm actually just not sure why this is even on the list. I've installed it, poked around, and can't actually find this feature implemented. Am I just missing it?

I'm also aware of Relation, which seems intended to supersede just about every other reference-ish module and I presume will do this. But it doesn't even have any released code at the moment, and this research is for something I'm working on right now, timeline of probably a couple months tops.

Are there any currently viable options for accomplishing this? I'm willing to guinea pig anything at least in beta status. Or do I need to give serious consideration to doing this in Drupal 6 instead?


texts: How do I add the ability to change font size in CKEditor?

texts:
I'm trying to install the CKEditor Font Size Module in my my editor. I installed the module via composer and then proceeded to copy the font/plugin.js file from the Font Plugin's page into libraries/ in my document root, per the instructions.

I also threw in a console.log() call into the font/plugin.js file to make sure it was loading. I modified the configuration of the Basic HTML editor to include the font size and family buttons in the toolbar on the /admin/config/content/formats/manage/basic_html page of my site. When I go to create a piece of content that uses the Text Editor, I don't see the font/size buttons I've configured.

Checking the Javascript console, I see my log message so I know the font/plugin.js file is being loaded. There are no error messages in the console. Why would the buttons not be showing up in this case?


texts: How to make a page look like it would have w/o tpl

texts:
Say, for example, I want to customize the edit user page, so I have created a user-profile.tpl.php. Is there a way to echo out what the page would be normally? What variables should I have access to?

I have tried var_dumping $node, $form, $page, $content, and $user_profile and all but the last are null...

print render($user_profile); results in a list of profile fields, but not the edit-user page that I get without the tpl file.. (where you can change password, email, etc.

I'm curious for pages/nodes/etc in general, not just this particular one. It's an issue I always struggle with.


texts: How to check whether multi value field is of type field_collection_item or not?

texts:
I am trying to check the type of multi value field is a field_collection_item or not inside computed field using this code:

$wrapper = entity_metadata_wrapper($entity_type, $entity);
$fields_info = $wrapper->getPropertyInfo();
foreach ($fields_info as $req_field) {

  if ($req_field['type']=='field_collection_item') {
    //do something here
  }
}

The if statement failed as $req_field['type'] returns list<field_collection_item>.

Any ideas?


texts: basic question: fast mobile site with omega

texts:
I would like to propose our company to make our site responsive. I thought to use the Omega theme as a basis. But one question before I dig deeper:

I would like to have a fast mobile version of the site that does not load all blocks and that just loads a few images and these ones in a small resolution.

Can I do this with Omega? Which other modules do I need?


texts: How to raise Notifications on new discussion posts?

texts:
How do I enable notifications for a user who subscribes to a Discussion Post section so that the user gets a notification when a new discussion topic is created by another user?

The notification should show up on his profile dashboard as well as sent by email.

Presently, the user dashboard has the block View - Open Atrium Content - Recently Updated Subscribed Content, but this block only shows updates for new comments on specifically subscribed content topics, not new discussion topics.


texts: How do I add another email address for PayPal email Notification?

texts:
I’d like to add a additional receiver email address for new orders to my Drupal Commerce site. I have added another PayPal receiver e-mail addresses to the the PayPal Express Checkout payment method using the Commerce PayPal module. (admin/commerce/config/payment-methods/manage/commerce_payment_paypal_ec). I am using the default Drupal rule for the PayPal Express Checkout module.

However the PayPal email Notification is not send out to the secondary email address. I don’t see any errors in the Drupal Logs. Do I have to add another email address within my PayPal seller account? I really appreciate any help.


texts: Best practice for displaying multiple views in a single page

texts:
I am working on a Drupal 7 website where there are many pages which utilize multiple views.

The way I am doing this right now is by creating a page from Drupal admin panel, and in the edit mode of that page I am calling views_embed_view to display those multiple views.

Other ways I could do this is by creating a template for that page, and putting my code inside the template.

Yet another way is to use View Fields View (https://drupal.org/project/views_field_view) and embed the second view inside the first one.

I want to know, performance wise which is the best practice?


texts: I created a new content type in Drupal 7, and added an image field named "field_photo." Can anyone tell me how I can extract the "href" attribute of that photo? Is there a short code I can use?


texts: Problem In Adding Flexslider To Slideshow

texts:
Hello i Have Create A Views Slideshow Using Views And Jquery Cycle But I Am Installing Flexslider Module But I Can Able To See A Slide Sidebar I Am Also Placing The Flexslieder Into Libriaries

Check My Link Adclof.com


texts: Cannot get just the text of an option from submitted data

texts:
I'm using Webform 8.x-5.8.
I've got a select box referencing some content. Of course, the numeric option value is passed. But when I reference submitted data with tokens, I just want to handle the plain text appearing with the options, but a concatenation of the text and the sequence " (NID)" is displayed instead, where NID is the content ID. An example with dummy code, names and values - just to roughly show what I suppose is happening behind - is following.
<select name="my_parameter">
<option value="80" selected>Some text</option>
...
...
...
</select>

By selecting Some text, "80" is passed.
My aim is displaying "Some text" picking it up from the submitted values.
Tried with [webform_submission:values:my_parameter] and [webform_submission:values:my_parameter:value].
Anyway I get Some text (80).
What am I supposed to do in order to get rid of that final NID in brackets?
Thanks in advance!
Andrea


texts: Fetch all fields of an entity and their data, for a simple clone Rule

texts:
I don't think this is possible out of the box in Rules, but I would like to create a Rule that clones an entity of a specific type.

Using for example a Rules Link as trigger, the The bundle type of the entity is known.

However, the Rules Link must work for all BUDLES of one entity TYPE. So I can't hard-code the fields in a Rule of which the data value need to be set.

Validating the existence of all fields is not possible since there are too many fields available in the entity TYPE.

Is it possible to make Rules 'fetch' the list of fields that are attached to a BUNDLE?
In that way, I can create a loop that copy pasts the field values from the original entity.


texts: Why is a blocked user showing up in my watchdog logs?

texts: Upon checking my error logs in watchdog today, I discovered an IP address that tried to go to a (non-existent) admin page. I have already blocked this IP and when I go to https://example.com/admin/user/rules/check and type in the IP address, I get the message


texts: I have a view with its filters exposed. when someone searches for any content results are shown perfectly in list view . now wat i want is a link showing grid view of the same result. more apecific i want a result to be in 2 modes  1) list view and another one is the grid view.


texts: How to use a views ajax pager to only reload the paged main view, not a display-all-items attachment

texts:
I have a view page displaying 5 items. The page has a views attachment displaying all items (a leaflet map display with about 200 nodes). The view uses ajax.  I find that clicking the views pager renders both the view and the attachment, even though the contents of the attachment are not changing between different pages. This is a performance problem.
Does anyone know of a way to prevent the pager ajax request from requesting new attachment markup? Is it possible to do this so that if the pager response doesn't return any attachment markup, it won't just blank out the attachment?
Should I consider making a custom pager that loads via ajax the paged result of a block of the same view, then writes the specific html region and rewrites the url, leaving the attachment alone?


texts:
Content type A:

Title
Address
Geocodes

Content type B:

Student Name
Major
University (This is prepopulated basing on Title of Content type A)

Now on the page which displays data from Content type B, I need to get the geocodes of Content type A, basing on University selected. How do I do this?

I have to get them to views-view-field-content-type-b-block-field-university.tpl.php where I am using the geocodes to display the data on a google map.

I am very new to Drupal, so any help would be hugely helpful. TIA.


texts:
I am trying to use user_save api. i have passed the following object ($user)

object(stdClass)#30 (6) {
  ["name"]=>
  string(12) "user_name"
  ["mail"]=>
  string(22) "myemail@gmail.com"
  ["pass"]=>
  int(1311514302)
  ["created"]=>
  int(1311514302)
  ["status"]=>
  int(1)
  ["roles"]=>
  array(1) {
    [0]=>
    string(10) "OauthUsers"
  }
}

I have used the following function:

$user = new stdClass();
$user->name = $userdata['name'];
$user->mail = $userdata['email'];
$user->pass = time();
$user->created = time();
$user->status = 1;
$user->roles = array('OauthUsers');
user_save($user);

I have tried to drop the "roles" property as well, but in all the cases user_save() returns FALSE.

Do you have any idea of what I am doing wrong?


texts: How do I move a https site to localhost?

texts:
I am moving a site from the live server where it has an SSL certificate and is accessed by HTTPS to my localhost. After moving the site over, I get an ERR_SSL_PROTOCOL_ERROR.

I am uncertain of how to fix the issue. I tried turning off Clean URLs before the move. And I also tried changing the .htaccess file.


texts: REST API Guzzle POST gives timeout but the same call works if I run it on the server cli

texts:
I have Drupal running in a docker container and nginx running in another container.

When I do the login call through postman or directly on the webserver cli it works perfectly.
But when I do call from within my application I get a timeout after 30 seconds.

From server:

  wodby@php.container:/var/www/html $ curl -X POST \
    'http://api.swappr.localhost/user/login?_format=json' \
    -H 'Postman-Token: a9c80844-ed69-4d24-b205-6475b7e469dc' \
    -H 'cache-control: no-cache' \
    -d '{"name":"logintest2@gmail.com", "pass":"password"}'
  {"current_user":{"uid":"21","name":"logintest2@gmail.com"},"csrf_token":"yf5YBYyY4YvXCcufLyTWeKnvbhq5sdcZHpgmsVDeSRY","logout_token":"PEarVS7vPi5idARarGQzrrXAYcJL9YkiXmoHw_a7yJE"}

In code:

$response = \Drupal::httpClient()->post(
            'http://api.swappr.localhost/user/login?_format=hal_json',
            ['name' => 'logintest2@gmail.com', 'pass' => 'password']
        );

cURL error 28: Operation timed out after 30001 milliseconds with 0 bytes received (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Anyone knows what could cause this problem?


texts:
I'm attempting to create a custom template for the search page located at

127.0.0.1/search/node

I've created a template called search-result.html.twig in my theme/templates folder which allows me to modify each search result but I'd like to actually modify the buttons and text fields at the top of the search page.

Is there a specific template that affects the search button and fields?


texts: How do I create hierarchical select for state, district, city, and location using AHAH?

texts:
I have a site for Indian tour places where I need to add the information for the "Location" content type.
For example, in http://www.indiantourplaces.com/andhra-pradesh/hyderabad/hyderabad/saroornagar-lake-51.htm we have the information for the location "SAROORNAGAR LAKE" which is located in India (country), Andhra Pradesh (state), Hyderabad (district), Hyderabad (city). I want to create all the above state, district, city as different nodes, and when I add the location details, I want to first select the state; then another list box will be populated with the list of districts which are present in that state, and once the district has been selected, another list box will be populated with the list of cities present in that district.

I am stuck up with this from may days.


texts:
I have few confirm_forms which could be invoked from different places. I would like to redirect user to proper place after cancelation. Referrer Header is not good way to do it so I'm looking for good idea to do it in drupal. Maybe something with current_path?

Menu for deletion is defined like so:

$menu['module/entity/%/delete'] = array(
    'title' => 'Delete directory',
    'description' => 'Remove directory from ITC Backup',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_entity_delete_form', 2),
    'access arguments' => array('Entity administer'),
    'type' => MENU_LOCAL_TASK
);

Form creation function is (at the moment) defined this way:

function module_entity_delete_form($form, &$form_state, $did) {
    $form['Id'] = array(
        '#type' => 'hidden',
        '#value' => $did
    );

    return confirm_form($form, t('Are you sure you want to delete selected entity?'), 'module/entity/list');
}


texts: Hidden form values updated with multiple submission

texts:
I'm writing a backend validation function to prevent multiple submission for comments by logged in users in Drupal. Following is my code:

function MYMODULE_form_comment_form_alter( &$form, &$form_state, $form_id ) {
        if( user_is_logged_in() ) {
          $unique_bytes = openssl_random_pseudo_bytes( 8 );
          $unique_id = bin2hex( $unique_bytes );
          $session_key = 'comment_form_token_' . $form['form_id']['#id'];
          $_SESSION[$session_key] = $unique_id;
          $form['one_time_token'] = array(
              '#type' => 'hidden',
              '#value' => $unique_id,
          );
          $form['#validate'][] = '_MYMODULE_comments_validate_one_time_token';
        }
}
function _MYMODULE_comments_validate_one_time_token( $form, &$form_state ) {
  if( user_is_logged_in() ) {
    $form_id = $form['form_id']['#id'];
    $session_key = 'comment_form_token_' . $form_id;
    $one_time_token = $form_state['values']['one_time_token'];
    if( isset( $_SESSION[$session_key] ) && $_SESSION[$session_key] === $one_time_token ) {
      unset( $_SESSION[$session_key] );
    }
    else {
      form_set_error( 'comment_body', t( 'Please make sure that you have submitted this form only once.' ) );
    }
  }
}

The problem is that when the user submits the form multiple times by clicking the Submit button extremely fast, the one_time_token field's value gets updated automatically rather than submitting the original value.

To elaborate further, if my initial field value on form load was e8ac1824bf894e12, session value for that was also e8ac1824bf894e12 and submitted value was also e8ac1824bf894e12. But on processing second submission, my session value is 153695ec028bf151 but I expect my submitted values to stay e8ac1824bf894e12 but somehow that also changes to 153695ec028bf151.

Is there a way I can prevent that?


texts: Is registering a controller as a service still frowned upon in D8

texts:
In the presentation given in Portland by Kat Bailey in May, registering a controller class as a service was highly discouraged, however a lot has changed since then and I wanted to check if this is still the case.

It is well supported in the code and you can route to actions in the controller you registered via reference to the service id, such as.

 defaults:
   _content: 'my.controller:myAction'

Rather than referring to the controller class directly.

I can foresee at least a couple of use cases, primarily at the moment it allows an easy option to override / extend an entire controller via replacing the service.

The only other way I know to do that at the moment would be to register an event subscriber to override all the routes to a particular controller which would be rather long winded. Views currently overrides individual routes controller actions this way to reset routes for views with paths (which makes sense as that is more of a path by path based surgical strike).

I don't won't to start down a path that turns out to be a big D8 anti-pattern, but if service controllers are bad, what is the alternative to allow simple replacement of a controller in another module?


texts: Use Privatemsg admin form in theme (Missing functions!)

texts:
I've exposed the privatemsg_list_view() form in my site theme with a bit of work and it's displaying well. However, updating message statuses or trying to delete bulk messages results in a sad error:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText: Fatal error: Call to undefined function privatemsg_list_submit() in [...]/includes/form.inc on line 1464

Now I know that privatemsg_list_submit() is indeed set as the form #submit handler and I know that it does exist, over in modules/privatemsg/privatemsg.pages.inc. Obviously there is a disjoint between /system/ajax and my template.

What needs to happen to make this work? Do I just have to attach the .inc file to the form handler somehow? I've tried playing with module_load_include() to no avail.

Suggestions?

Update: The only place I have tried adding the module_load_include() function is directly before the function call in /includes/form.inc - that would have been somewhere just before line 1464. Obviously that was just a hack for troubleshooting purposes... should the module_load_include() function be placed somewhere else?

For reference: Call to undefined function privatemsg_list_submit()

Update 2: I have also tried inserting module_load_include() in a custom module_init() function as well as inside the theme hook_form_alter() - no luck.

Update 3: Manually including the file within a module_init() hook makes it work. Here's what it looks like:

function MYMODULE_init(){
    if($_GET['q'] == 'system/ajax'){
        if ( preg_match('/privatemsg_list/', $_POST['form_id'])) {
            include('/great/big/system/path/web/sites/all/modules/privatemsg/privatemsg.pages.inc');
        }
    }
}

While this appears to work on the surface, I'm sure it's not the right method. Is there a better function hook to use to include this file?


texts: Can we provide an inquiry form for products in ubercart ? I want to provide a form to each product so that the user can send his/her requirement to site owner. Site owner can later on check who has contacted him and why. I do not want to provide add to cart option.


texts: How to track down possible module conflict?

texts:
I am trying to get the SMTP Authentication Support module working on my development site. Whenever I try to send a test message, I get the error "SMTP -> ERROR: Failed to connect to server: Permission denied (13)." Our SMTP server is configured to accept relay from any client on our internal network, which is where my server lives. When I look at the logs, I see two errors - one of type "mail" and one of type "smtp".  Each say about the same thing.  This leads me to believe that the SMTP module is conflicting with something, but no other modules are currently installed.  I have tried/removed other versions of the SMTP module and the PHPMailer module.  I can't find a "mail" module in the Core section, so I don't think that's it.

When I install the module on my local machine, in a clean Drupal instance, with all the same configuration settings, the test message flies right through.  So, I'm guessing that maybe one of the other modules left some cruft behind in the database somewhere, and this may be causing a conflict with the SMTP module.  However, I don't know how to hunt down and eradicate the problem.

Any ideas?


texts: Set a numerical field to perform Views Global Math Expression calculations

texts:
Lets say I have three fields:

Field1 (a decimal)
Field2 (another decimal)
Global Math Expression

And in Global math expression I want to calculate [field1] + [field2]. How do I force Views to understand the replacement fields used in this global math expressions as numbers for calculation? As it is, it always returns the value 0.


texts: Is there any way to reuse the same file or image?

texts:
Is there any way to reuse the same file or image  while uploading
I just worry about having multiple/duplicate image files on the server - in time it could get full and slow down the server.

I have used FileField Sources module but I think its not compatible with drupal 8 its not showing configuration setup, any other alternative?


texts:
How do I construct an entity condition so that it loads current revision of all nodes? This is my attempt.

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'xxxxx')
->fieldCondition('xxx_module','tid', $tid,'=')
->age(FIELD_LOAD_CURRENT)
->execute();

Instead of loading the current revision, it loads the published revision.


texts: Current Password issue for New Register User

texts:
My registeraion is set to "Require e-mail verification when a visitor creates an account" on Drupal 7. Any user who register will automatically receive a confirmation email with "One time login url". However the problem is, user does not have the "Current Password" to set their new password. How can I fix this?

PS: user does have current password on database "users" table

added info:
using module logintoboggan

added on July 2nd:
I found a similar issue from Durupal.org, but i dont wanna use another module to solve this issue.


texts: Display formresults in same block as form

texts:
I have created a module that writes a block with a very simple form in it.

The purpose of it is calculating distance between 2 adresses, one fixed, one asked by the form.

Now I can't get the results to show in the block itself, and I can't find any tutorials on how to do that.

The block shows, the form is in it also, but when i submit a postalcode it seems that nothing happens (also the postcode input field resets to emtpy).

the code that retrieves the distance works also (tested on commandline).

How can I approach this?

The code for my block:

  function reiskosten_block_view($delta = '') {
  $block = array();

  switch ($delta) {
  case 'reiskostenblock':
  $block['subject'] = t('Reiskosten berekenen');
  $block['content'] = drupal_get_form('reiskosten_form');
  break;
  }

The code for submitting the form:

function reiskosten_form_submit($form, &$form_state) {

/* REPLACE SPACE OR HTTP-REQUEST WILL BE MALFORMED */
  $postcode = str_replace(' ','',$form_state['values']['postcode']);

  $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=1024AA|Netherlands&destinations=$postcode|Netherlands&mode=car&language=nl-NL&sensor=false&key=myKey";

$data = drupal_http_request($url);
$result = drupal_json_decode($data->data);

$destination = $result['destination_addresses'][0];
$distance = $result['rows'][0]['elements'][0]['distance']['text'];
$duraton = $result['rows'][0]['elements'][0]['duration']['text'];

  drupal_set_message("$distance");
  $form_state['rebuild'] = TRUE;
}

I want the output of $result to be shown below the submitbutton. It is driving me crazy this one, been puzzling for 5 hours now on this thing (what should be relatively simple imho).

edit:
I also validate on postalcode with:

function reiskosten_form_validate($form, &$form_state) {
  if ( empty($form_state['values']['postcode']) ) {
    form_set_error('postcode', t('Postcode mag niet leeg zijn'));
  }
}

It doesn't throw an error so it seems to me that 'postcode' has a value and the function should be processed.


texts: Edit Authorization form using theme callback and theme template

texts:
I'm trying to remove sections of an authorization form that is in a contrib module oauth2 sever module, but it's not working and I get the following warning :  Warning: Illegal offset type in isset or empty in drupal_theme_access() (line 53 of /Applications/MAMP/htdocs/drupal/includes/theme.inc).

This is the code that i used:

function test_menu_alter(&$items){
  $items['oauth2/authorize']['theme callback'] = 'test_theme';
}

function test_theme() {
  return array( 'test_theme' => array(
    'render element' => 'form',
    'path' => 'sites/all/themes/test',
    'template' => 'test',
    ),
  );
}

The contrib module menu item has a page callback which performs a number of checks before returning a form callback. Essentially I want to remove the header and page bottom from the authorization form. The template theme that I am using is:

<?php?>
<!DOCTYPE html>
<html>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <?php print $page_top; ?>
  <?php print $page; ?>
</body>
</html>


texts: Is there an optimal method to grant permissions for a newly added permission defined by hook_permission?

texts:
I'm attempting to deploy a new permission and granting in a single update.

I have custom.module which defines a new permission with hook_permission:

function custom_booking_permission() {
  return array(
    'custom allow registration' => array(
      'title' => t('Fill out Registration Form'),
      'description' => t('Allows a user to register their online account.'),
    ),
  );
}

And then in the custom.install in hook_update_n:

function custom_booking_update_7002() {
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('custom allow registration'));
}

The problem is that when I deploy this code and run drush updb -y in my script, I get this error:

  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null                                       [error]

Which as I understand it is because Drupal has yet to recognise the new permission in hook_permission.

I have other aspects to the update script such as enabling modules and reverting features, and then running drush updb later in the script works fine. However I've always believed that drush updb should be as early as possible. Maybe I just need to be more flexible.

Alternatively I was thinking about either an SQL insert to avoid the grant permission validation, or running a drush php-eval later in the deployment script separate from drush updb. Both strike me as undesirable.


texts:
I have a module with batch operations, this is my hook_menu

$items['some-pretty-url'] = array(
    'title'            => 'Title',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('import_form'),
    'access arguments' => array('access content'),
    'type'             => MENU_NORMAL_ITEM,
);

...and this is my batch config

$batch  = array(
    'title'            => t('Lorem ipsum Elit pariatur Duis et elit aute.'),
    'init_message'     => t('Commencing...'),
    'operations'       => $operations,
    'progress_message' => t('Processed: @current out of @total.'),
    'error_message'    => t('An error occurred during processing.'),
    'finished'         => '_import_finished',
);

Batch works pretty good if I have the module definition in the .module file, but if I move the functions to another file the batch simply does not work at all.

$items['some-pretty-url'] = array(
    'title'            => 'Title',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('import_form'),
    'access arguments' => array('access content'),
    'type'             => MENU_NORMAL_ITEM,
    'file'             => 'module_definition.inc', //move module to another file
);

$batch  = array(
    'title'            => t('Lorem ipsum Elit pariatur Duis et elit aute.'),
    'init_message'     => t('Commencing...'),
    'operations'       => $operations,
    'progress_message' => t('Processed: @current out of @total.'),
    'error_message'    => t('An error occurred during processing.'),
    'finished'         => '_import_finished',
    'file'             => 'module_definition.inc', //batch functions are here
);

Batch function is not being called even if I set the file argument in the batch configuration.


texts: Search settings: Indexing status stuck on 0%

texts: When I click Re-index site, and confirm, I get a message that the index will be indexed but it never does.


texts: Always load additional data from referenced (child) entity

texts:
I created some custom entity types, let's call them "parent_entity_type" and "historic_data_entity_type". The parent entity type is referencing to historic_data_entity_type indicating which data is currently up to date and historic_data_entity_type has a field referencing to the parent for a full historic overview.

I want to have a parent entity always be fully loaded with data from referenced historic entity as soon as possible during the entity loading process. Therefore I would prefer to do it in my custom entity class or somewhere at this level instead of using hook_entity_load or similar hooks which are called later in the process.

Is there somebody who can give me a hint how to achive that? Looking at Entity::load() I feel that I might need to setup some sort of custom EntityStorage.


texts:
I have a Drupal 7 view that uses fields as display type.

There are three fields, and I don't want to show the row if any one field is empty.

Currently, I am adding a filter for each of the three fields to achieve this. meaning if I have 20 fields, I would have to go for 20 filters.

Is there an easier way of doing this?

P.S. I can do this by overriding the row style output template file, and then add some custom php code. But I want to know is there an easier way using the views administration interface.


texts:
Since updating to 8.3 we've noticed that some URL's in our REST responses are being escaped (this may have been happening before but I don't think so as it is now causing issues with the Android parser).

The URL's are escaped like this;

{"_links":
    {"self":
        {"href":"http:\/\/example.com\/api\/resource\/80?_format=hal_json"}

Those w's (//) and v's (/) are killing things and I'd like to remove this escaping.

BTW, this API is password protected and used by a controlled app only. While removing this escaping may introduce issues with public API's and security/stabiliy, we don't need this level of control.

Can I just override the Serialize class and use that?


texts:
Given the following element in my webform, how do I print Name: Fred in my email?

Title   Key   Value
Name    name  Fred

I understand how to print the raw value. How do I print the title?

[?]: [webform_submission:values:name:raw]

An admin may change the element's title, so I can't have Name: [webform_submission:values:name:raw].


texts: Apache Solr 4.6.0 installation and compatibility with Drupal7

texts: I'm having difficulties installing Apache Solr. The latest version that I downloaded was 4.6.0.  But all Drupal documentation and tutorials (see http://www.youtube.com/watch?v=ori-VvvH1Aw) are talking about 3.5.0.  While 3.5.0 is nowhere to be found on internet, 4.6.0 has a totally different directory structure, and there is no documentation on how to install this latest version on a server or on a local WAMP.  There is no mentioning of which Apache Solr versions are most recommended to work with Drupal?  Any help?


texts: Looking for Acquia Dev Desktop database settings

texts:
I am using Acquia Dev Desktop to create local Drupal installations. I am also using Bluehost as a service. Unfortunately, Bluehost uses table prefixes for Drupal tables.

So, if I import something locally from BlueHost, I need to set a table prefix in the settings.php:

array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'port' => 3306,
  'prefix' => 'myprefix_',
  'collation' => 'utf8_general_ci',
);

Unfortunately, I can't find the proper database settings for the local Acquia MySql database. Acquia does not create a setting.php file on fresh systems too.

Does anyone know those settings? Thanks.


texts: Commerce checkout does not work when loading from AJAX

texts:
In D7, I have a dropdown form field that has an #ajax attribute pointing to a callback function that triggers when the drop down value is selected. In the callback function, I load the current Commerce order and then the Commerce checkout form using:

$commerce_form = commerce_checkout_router($order);

I then render the checkout form and display in the template:

$commands[] = ajax_command_html('#checkout-section', '');
$commands[] = ajax_command_append('#checkout-section', render($commerce_form));

return array('#type' => 'ajax', '#commands' => $commands);

When I do that, it looks like my checkout form does not get properly bootstraped and I lose all the interactivity of the checkout form I've set up using hook_info's etc.

When I visit the checkout form without AJAX everything works well.

Do I need to somehow bootstrap Drupal Commerce inside AJAX callbacks if I want to use AJAX so all my hooks that customize the Commerce Checkout?

PS: I am doing a

require_once '../contrib/commerce/modules/checkout/includes/commerce_checkout.pages.inc';

inside the callback. Without this I get functions not defined errors on core Commerce functions. (The Drupal Commerce and all related modules are enabled and it only happens in the AJAX callbacks.)

Thank you


texts: Disable Product Display upon purchase of the Product or it's variations

texts:
I have a site of products wherein each Product Display has 2 Variations (Products).

I would like it so when a single variation is purchased the Product Display get's unpublished (regardless of a variation still being available for purchase).

I've been trying to do this with Rules with little success, has anyone come across this before or know of a solid solution?


texts: Feeds Importer Xpath import where guid is at the top of the context

texts:
Trying to import from an XML feed using Feeds Importer XPath XML. I have had an import working from this same feed before but with uniqueness based on a title field which is no longer apropriate.

I'm trying to alter the import so that I now use a guid. The problem is that the ID I need to use is only located within the top level element where the context starts.

XML looks like:

<vacancies>
  <vacancy id="111427">
    <uri>https://data.ox.ac.uk/id/vacancy/111427</uri>
    <url>https://data.ox.ac.uk/doc/vacancy/111427</url>
    <webpage>https://www.recruit.ox.ac.uk/pls/hrisliverecruit...</webpage>
    <label>Postdoctoral Scientist - Protein Biochemistry</label>
    <opens>2014-01-16T09:08:14+00:00</opens>
    <closes>2014-02-17T12:00:00+00:00</closes>
    ...

My context is
    /vacancies/vacancy
and I am mapping my guid to @id which I think is the correct syntax.

The import doesn't work correctly, I get no nodes and no errors. What am I doing wrong (if anything)? There is nothing I can do about the XML schema incidentally, if that is where the problem is.


texts:
Can anybody explain me why the right way for programmatically saving a line item object with Drupal Commerce is the following one?

commerce_line_item_save($item);
entity_get_controller('commerce_line_item')->resetCache(array($item->line_item_id));

I wish to be smarter after knowing that.


texts: When using Zen and Zen grids, where do I put SASS variables?

texts:
I am trying to use Zen Grids with the Zen ver. 5 starter theme.

The Zen starter theme comes with a lot of .scss files (in the sass/ subdirectory).  I am trying to use Zen Grids to set up a simple layout.  I've read up on Sass and think I understand the concept, and I've Compass installed and working.

I've read everything on the Zen Grids website. On the front page of that website, below the promising headline: "Using Zen Grids is easy!", there is a nice introduction to Sass and Zen Grids followed by: "And here’s the complete Sass code:".

The example is strightforward enough.  What I am not able to figure out is where (as in "in what file") you put the statements used in the example.

(My setup is a Zen sub-theme created from the Zen STARTERKIT, straight out of the box.)


texts:
I have the following items configured in:
Home » Administration » Configuration » People » Account settings

The problem I have is that I want to display user email and timezone.  On the "Manage Display" these fields are not shown so I cannot configure them.  Note that I am using the "Email Registration" module to allow users to register with email and essentially hide their user_id.   Here is the display page.

Note: when I display email it shows like this instead of showing the actual email which does exist:


texts: How to get field mapping information in custom module?

texts:
I am trying to call field_info_field_map() in my DefaultForm.php . What is the right way? I am getting the following error:

  Error: Class 'Drupal\module_name\Form\Field' not found in
  Drupal\module_name\Form\DefaultForm->module_name_settings_get_field_options()

The code I am using is as follow:

$fields = Field::fieldInfo()->getFieldMap();

the code i am trying to convert to d8

function mn_settings_get_field_options() {
  static $options = null;
  if (is_array($options)) {
    return $options;
  }
  $options = array();
  $fields = field_info_field_map();
  foreach ($fields as $field_name => $field_data) {
    if (isset($field_data['bundles']['node'])) {
      $node_types = $field_data['bundles']['node'];
      $options[$field_name] = $field_name . ' (In content types: ' . implode(', ', $node_types) . ')';
    }
  }
  asort($options);
  return $options;
}


texts: Best way to translate parts of an existing site and retain page aliases

texts:
What is the least complicated way to translate parts of an existing and quite big site (few hundreds of thousands nodes), without affecting the page aliases?

I am aware of different translation systems and would prefer to use Entity translation. Unfortunately, it seems that both Entity Translation and Content translation don't make it possible to retain a functioning URL structure. E. g. I have this now:

Original text's URL (the same pattern should work after translation): example.com/texto-original

After the translation work, it should have this structure:

Original text's URL (the same pattern should work after translation): example.com/texto-original
Translated text (has language parameter in the URL): example.com/en/translated-text

What I want to achieve:

There's a default language (Spanish in this example) that was used for all of the content so far. Those pages don't have language prefix in the URL (e. g. "es/") at the moment. It should stay that way.
Site should always display everything in Spanish, unless a visitor opens an URL with "en/" prefix.
On the pages that are translated, there should be a link "English", "View this page in English" or something similar.
When a visitor opens such page in English, there should also be a link "Español". If a visitor is on the English page - the interface, blocks and other entities (if translated) should be in English as well.

Sorry if I haven't explained well what I want to achieve, I'll try to explain better if something is not clear.

Thank you for any ideas.


texts:
For the filter block I need to get the data from database. I have three tables "node", "node__filed_country" and "taxonomy_index". So I need to pull only those taxonomies which are realted to the nodes, which field_country is equal to three particular countries. So I need to provide two joins.

$query = $this->connection->select('node', 'node');
$query->join('node__field_country', $nfc, "node.nid=$nfc.entity_id and ($nfc.field_country_target_id=1 or $nfc.field_country_target_id=2 or $nfc.field_country_target_id=3)");
$query->join('taxonomy_index', $id, "$id.nid = node.nid AND $id.tid = $term->tid AND $id.status = 1 ");
$query->execute()->fetchField();

But something doesnt work in this code. Could you please help me?


texts: Best way to display PDF in drupal as a slideshow

texts:
I'm looking to display a PDF on a page, but don't want to outsource the hosting to scribd or slideshare, or one of the other players.  My constraints are basically...

I want to host it on my site.
I want it to look like a slideshow (can click to go forward, navigation backward, etc.)
I want most users to have whatever they need to access it already (ie, if it's SWF, fine.)
I want the whole PDF to be downloadable easily, as a PDF (rather than SWF, etc).

Does anything fit that bill?  I saw on stack overflow, at one time the answer was no.

https://stackoverflow.com/questions/291813/best-way-to-embed-pdf-in-html

But wondering if the Drupal way can offer any better.


texts: Print image field path in views-view-fields--key-projects.html.twig

texts:
I am working with Drupal 8 and trying to print some fields through a twig file.

Created:

A view (format:grid)
A content type (fields: title, body image)
Contents

File working on:

views-view-fields--[machine-name].html.twig

To Do:

How can I print the path of the image in the content?
How can I print the path of the node/content on a Read More link?


texts: How can i have a SimpleNews signup form as modal/lightbox

texts:
Is it possible to have the Simplenews sign up form block as a modal - I'd like to present people to the signup a bit more visible than a static block.
Would i be possible to present the modal when eg. 3 pages have been viewed. Assuming that visitors with 1-2 page views would not be interessted in a newsletter.


texts: Conditionally show fields viewing a node (not in the node add form)

texts:
I know conditional fields can be use to create CCK optional fields, but I need something similar to display part of a node, according to user decisions.

I will have a question "do you like cats?", then the user will be shown another question according to what they answer to the first one, and so on.

I was thinking to create this all in one node

field1 -> answer 'yes' -> show field2,
field1 -> answer 'no' -> show field3),

but I guess this could be done the same with multiple nodes

node1 -> answer 'yes' -> show node2,
node1 -> answer 'no' -> show node3.

Do you have any module to suggest me to reach my goal?


texts: Enabling a module leads to memory exhaution. Where to look for?

texts:
I have developed my little module for Drupal 7 and it has been working fine.  But suddenly it started to cause a memory crush.  Now I can't even enable it (drush en ModuleName) with the error message of:

  Error: Allowed memory size of 536870912 bytes exhausted [...] in /MY/DRUPAL/ROOT/includes/module.inc, line 596

The line number, where it fails, varies sometimes.  I clear the cache (drush cc all) frequently or practically at every step, so I don't think it is cache-related. The allowed memory for PHP and SQL are both 512MB, and the website is mini-scale with no load-hungry module.  The memory should be a way more than enough.

The module is just a little language switcher with only a *.module file (and *.info), and has no major loop — One time loop for an enabled couple of languages is all it has.  No recursive call whatsoever.  So, I have no idea where to look for to pin down the problem…  Only the potential thing I could think of is I had deleted a (unnecessary) path-alias directly via SQL (a row in Table url_alias), immediately before this trouble started.  It being the language-switcher, it accesses to drupal_get_path_alias(), but does it matter?

In case you are interested, my little module is available in GitHub:
https://github.com/masasakano/lang_switcher_advanced

[Edit]
It seems the problem was tracked down and I posted it as the answer.  Everything one'd need is written in it, but just to note, the example codes before and after it was solved are tagged as 0.1.1 and 0.1.2 in the above GitHub repository.


texts: Autocomplete on a custom field on the registration form no longer working

texts:
thanks for reading.

I have a database table containing organisation names. When a user registers on the website, they use a text field I added, which autocompletes with existing organisation names, as a way of attaching them to existing organisations. This used to work fine, but doesn't seem to now, presumably after one of the updates. Now it simply doesn't load anything when typing in, though the little circle appears to indicate that it is connected.

Here's the code:

$items['org/autocomplete'] = array(
  'page callback' => '_org_autocomplete',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK
);

...and...

function _org_autocomplete($string = '') {
  $matches = array();
  $query = db_select('org_orgs', 'c'); // I've checked that the table exists, contains data, and is of this name - that's fine
  $return = $query
    ->fields('c', array('name'))
    ->condition('c.name', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  foreach($return as $row) {
    $matches[$row->name] = $row->name;
  }
  if ($_SERVER['HTTP_REFERER'] == url('user/register', array('absolute' => TRUE))){
    drupal_json_output($matches);

    // The if statement surrounding this line prevents users
    // from viewing the full list by going directly to the
    // /org/autocomplete URL. In removing the if statement, I can
    // test to see if it works at the URL, and it does just fine

  }
}

I've checked that the table exists, contains data, and is of this name - that's fine. The if statement surrounding the drupal_json_output() line prevents users from viewing the full list by going directly to the URL. In removing the if statement, I can test to see if it works at the URL, and it does just fine.

function org_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_organisation']['und'][0]['value']['#autocomplete_path'] = 'org/autocomplete';
  // Though no results appear, the 'org/autocomplete' path
  // is confirmed as the correct path because changing it to
  // anything else removes the little autocomplete circle.
  $form['field_organisation']['und'][0]['value']['#description'] = 'If your organisation appears in the above predefined dropdown menu, please select it.';
  $form['#validate'][] = 'org_form_validate';
  $form['#submit'][] = 'org_form_submit';
}

Though no results appear, the 'org/autocomplete' path is confirmed as the correct path because changing it to anything else removes the little autocomplete circle.

Do you have any ideas of what's gone wrong, or if not, what I can do to investigate?

Additionally, in searching for the solution, I found this drupal update: http://drupal.org/node/1901518 Could this be the cause? And if so, what can I do to correct it?

Thanks


texts:
I installed the Frequently Asked Questions module and have created questions and answers.

I navigate to /faq-page and all I see if the title of the page "Frequently Asked Questions", but I don't see the actual questions.

I made sure:

The content is published
Permissions have been set
There is a valid 'Views' page

I even tried creating a menu item and that 's not working.

Can anyone help?


texts: field collection - taxonomy term can't display

texts:
I used taxonomy term with field collection and taxonomy term can't display
look this video

https://www.youtube.com/watch?v=cEI1yDcJXT4


texts: Drupal UberCart how can users see thier own orders

texts:
I'm setting up a shop on one of my sites, and I've set it so users create an account when they order. When users log in, I cannot workout the link to show their past orders, or registered addresses.

Is there anything built into UberCart for this? All I've found are some permissions and I've set "View own order." Do I have to write up a module for this?


texts: What is efficient way of updating drupal commerce product prices when your on a product display page?

texts: What are some fast ways of updating the product prices for drupal commerce? Right now i have to go into the product list and search for the items I want to change prices on. I know inline entity form solves the issue, but was wondering what other methods are other people doing?


texts: How to get a backtrace in Drupal, without problems like out-of-memory when huge objects are in the trace?

texts:
I often have problems with the standard backtracing functions when working with Drupal:

debug_print_backtrace(); often seems to get lost between pages and never prints,
Drupal's objects and classes are often so big that debug( debug_backtrace(), "Backtrace", true ); can kill my server with out of memory errors, and debug( debug_backtrace() ); almost always fails with a "Nested dependency" recursion error.

Is there any alternative to the above approaches that can be used reliably, ideally as a drop-in function without needing to set up any framework?


texts:
I want to move my drupal site onto another server. I installed drupal using drush & copied the sites/ directory to where its suppposed to go. I then copied the database and changed credentials in settings.php - all seemed to make perfectly sense to me up to this point, wen i now go to update.php, I get this error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'u.uid' in 'on clause': SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid; Array ( [:sid] => abcdefg ) in _drupal_session_read() (line 102 of /home/quaaout/public_html/drupal-7.34/includes/session.inc).

I'm wondering what this means and how I get my site up on the new server? What is a PDOException?

UPDATE 1

@PatrickRyan What I did is, I backed up the db using my GoDaddy interface on the old server, downloaded it to my local machine and uploaded it to my new server, creating a db with the same name as on the old server -> I changed the settings in settings.php to connect to the newly added db and that's how i'm getting that error. Where's my procedure wrong? What alternatives should I try?

UPDATE 2

Okay, what I did exactly, I backed up my old db using the GoDaddy Mysql backup utility (old server) and it stored the whole db in a file in my ftp under _db_backups. I downloaded that file and uploaded it in my GoDaddy cPanel (new server) under MySQL- Backup - Restore a MySQL Database Backup. That's created a new db in my cPanel featuring the same name as on my old server. I setup user and password, assigned it this db, verified that I can login from the shell but when I go to my URL, I still get: an error that says

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'u.uid' in 'on clause': SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid; Array ( [:sid] => 9uLxQl2polstrF1s6iYenrU1oB9M_rf0fecWUaI_FIs ) in _drupal_session_read() (line 102 of /home/quaaout/public_html/drupal-7.34/includes/session.inc).

underneath the error it says:

  Uncaught exception thrown in session handler.
  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column 'uid' cannot be null: INSERT INTO {sessions} (sid,
  ssid, uid, cache, hostname, session, timestamp) 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); Array ( [:db_insert_placeholder_0] =>
  9uLxQl2polstrF1s6iYenrU1oB9M_rf0fecWUaI_FIs [:db_insert_placeholder_1]
  => [:db_insert_placeholder_2] => [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => 174.6.222.12 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] =>
  1426465727 ) in _drupal_session_write() (line 209 of
  /home/quaaout/public_html/drupal-7.34/includes/session.inc).

What am I doing wrong??? :o


texts:
I have a module which reads in csv file and adds records to the database. It is working properly on localhost. I am able to upload the file and read and then display the result. But, on my server, i am able to upload the file but this piece of code fails, while reading the file.

 $file_handle = fopen($file_url, "r");
 while (!feof($file_handle) ) {
 $line_of_text = fgetcsv($file_handle, 1024);
 print_r($line_of_text);
}

I realized that it might be a permission issue so , i checked that folder has got 0777 permission where as i am not able to give recursive permission to files, files have permission of 0664. and i get access denied when i try to give it different permission, i am on ubuntu server.
After i checked

 $file_handle = fopen($file_url, "r");
 var_dump($file_handle);

On localhost i got: resource(90, stream), whereas on my server i got bool(false).


texts: How do you switch a site's language by using GET variables? Is there a module?

texts:
Currently I'm using a module that displays a bunch of nodes on a single page.

And I also have translated content in different languages.

The core functionality to switch a sites language currently creates a prefix in the URL, but is there one for switching the language via a GET variable like www.example.com/node/8?lang=german?


texts: Cloning content types and corresponding Display Suite settings

texts:
I need to clone a content type, so I choose to do that with module: Bundle copy.

I need to clone Display Suite settings of my bundle as well. How would I clone that? (Found a patch that enables that with Bundle copy: https://drupal.org/node/2055157). Wondering is there any better solution?


texts: What is Best Way to Retrieve Status Messages in Multiple Locations?

texts:
We like to share the status messages in multiple location in single request, so we retrieve them:

function get_messages(){
    $status_messages = array();
    //loop through each message type
        foreach (drupal_get_messages(null, false) as $type => $messages) {
               foreach($messages as $key => $message){
                   $status_messages[$type]['enabled'] = true;
                   $status_messages[$type]['messages'] = array(
                       'message' => $message
                   );
               }
        }
return $status_messages;
}

Here, since we are passing "FALSE" to the drupal_get_messages function the messages are not reset which is what we like because multiple locations gets to call this function, however. At some point, the messages need to be reset.

One option is to clear messages at the last point of the request.
Where and how to do that?
Another option, would implement a cache
and run drupal_get_messages() with "TRUE" to call once and reset at
the same time. I am not familiar with cache in Drupal or PHP. How to
do that?

In short, we like to access status messages in multiple locations and $variable['messages'] is not available to serve the purpose. How to do that? Thank You for help


texts:
How can I put a condition on the Header in a View to not display the Header if the View has content?

There's an option to display a Header/Footer absent any content, but I'm looking for the opposite effect.


texts: User added to a specific group should be blocked

texts:
I'm trying to accomplish the task -" If the User is added to a specific CiviCRM group manually by admin/'users with permissions to add to group', The added user should be blocked.I'm using Rules module with CiviCRM entities.

Here is my Rules export:

{ "rules_block_unblock_user" : {
    "LABEL" : "Block\/unblock user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm_entity", "rules", "civicrm" ],
    "ON" : { "civicrm_group_edit" : [] },
    "IF" : [
      { "civicrm_entity_contact_is_in_group" : {
          "civicrm_contact" : [ "site:current-user:civicrm-contact" ],
          "group_id" : "2"
        }
      }
    ],
    "DO" : [ { "user_block" : { "account" : [ "site:current-user" ] } } ]
  }
}

I guess I'm not selecting the right data selectors. Any help?


texts: How can I get the content of a mini panel that is limited to admin-only access using a scheduled rules component?

texts:
I'm using Rules to e-mail myself the content of a Mini Panel, which contains several views that are restricted to admin-only access.

I am using a component (Action set) that consists of two actions:

Send e-mail
Schedule component evaluation (re-schedule the same component to be evaluated the following day)

For Send e-mail, the body of my message looks like this (based on this code):

<?php $block = module_invoke('panels_mini', 'block_view', 'admin_user_role_statistics'); print $block['content']; ?>

When I first triggered this component (using a rule that I created to trigger the component for the first time by viewing a user profile), I was logged in as an administrator, so the e-mail I received shows all of the content of the mini panel as I expected.  However, the following day, when the scheduled component was evaluated, the body of the e-mail message was blank, presumably because it was not sent by an admin user.

I re-enabled the rule to trigger the component and tried it as a non-admin user: the message body was empty.  I then tried it as an administrator: the message had the full content.

So, what can I do to make sure the component is evaluated as if triggered by an admin user?


texts: How do you include a translatable string in an update hook

texts: In D7 you had to use get_t() in order to include translatable strings in an update hook. Is there a similar procedure for D8?


texts: How do I programmatically load an order by its properties?

texts:
I know how to load an order by its ID using \Drupal\commerce_order\Entity\Order::load($order_id). I added a custom field (Token ID) to the orders.

How can I load the orders knowing the value of that field? If I want to get the state of the order, how can I achieve it?


texts: How to map a taxonomy term into Feeds Importer?

texts:
I have several Blank sources in a Feed and I'm mapping a value to these blank sources in my custom code.

I have a working example to set a value of a field of type 'TEXT FIELD':

function set_profile_value(FeedsSource $source, $entity, $target, array $values, array $mapping) {
    if (substr($source->id, 0, 7) == 'my_data') {
        if (!empty($mapping['profile'])) {
            $entity->{$target}[$entity->language][0]['value'] = $mapping['profile'];
        }
    }
}

My question is, how to do the same if the field is a term reference?

Thanks!


texts: How to add a custom javascript code in a Drupal BLOCK

texts:
The title says it all. I want to add a series of advertising javascript code like adsense, facebook likebox javascript code.

How can I add a javascript code as a block and put it on sidebar first. Its not working for me even typing the javascript as FULL HTML but instead drupal displays the source code in my sidebar instead of executing it as javascript.

Can I just COPY PASTE the javascript code in Drupal block, is this possible?

Note: I am using Drupal 8


texts: What files will Drupal poll for hooks by default?

texts: I tried implementing hook_menu() in an foo.admin.inc file for reasons that aren't important, and discovered that hooks are not checked in said file. However, in the past, I have seen include files with hooks defined in them (e.g. rules.inc), so I was wondering what the default core rule is for this, and how one can specify files outside of the defaults. Does extending where hooks can be checked have a nice Drupal way of doing this, or have module developers used PHP to achieve this end?


texts:
I have a Drupal install on a CentOS development server. Running drush from outside my web directory returns as you'd expect (a list of Drush commands).

Running drush from inside my web directory returns nothing at all. Running with debug returns this:

Using the Drush script found at /home/***/vendor/drush/drush/drush using pcntl_exec
[preflight] Config paths: /home/***/vendor/drush/drush/drush.yml
[preflight] Alias paths: /home/***/drush/sites,/home/coventry/drush/sites
[preflight] Commandfile search paths: /home/***/vendor/drush/drush/src

When using Drush from outside my web directory with --root, I get this:

drush uli --root=~/***.com
We could not find an applicable site for that command.

My settings.php file exists in that above directory/sites/default, and the database connection info works. The site is accessible in the browser.

Any ideas on this botched Drush install?


texts: Custom block.tpl not affectiong all blocks

texts:
I have a custom theme and in the templates folder I have copied block.tpl and changed H2 to H3 and added a CSS class to the content div. Changes are taking affect and drupal is loading my block.tpl but all blocks are not getting affected, only some. Some of the blocks which are not getting affected are Book navigation block, navigation block etc.

How do I make all blocks affected by my changes to the base block.tpl.php ?


texts: How to split content over different regions... views?

texts:
I have a client who wants to allow some editorial staff to create and edit 'main pages' on their site. These are things like 'about us', 'our clients', 'breaking news' and so on; they want these 'main pages' to follow a house style (one main image, relevant links here, block quote there, content in the middle, etc.)

The site is built with Drupal 7.

I'm thinking that the way to go is probably using a custom content type, 'main_article' and then using views to display various fields from that content type in the relevant blocks - so, for example, having a 'main content' block that sits in the content region and displays the title and main content, 'picture' and 'links' blocks that both go in the left column, and 'citation' and 'blah' blocks over in the right column.

I guess I would use the 'Content: NID' contextual filter to make sure that I only get content from the relevant 'main_article'.

This seems like a standard enough design issue: Am I going about it in the right way?
Is there a better solution?  (I've seen similar questions here and elsewhere that led me to follow this way of doing it.)
How would I go about getting the 'main_article' content type to put a link in the main navigation menu?
Using the menu option in the content creation page would link to the default content, not the view (if you see what I mean). Could it be done using a field?
If the user creates a URL Path for the content they create using this content type, that's going to break the 'content: NID' contextual filter. Is there a way of 'contextual filtering' on the URL (which should then work for standard node URLs and for 'nice' URL paths)?


texts:
In drupal 7, I created a content type called page and set the url to /about. If I check the source code I see

<link rel="canonical" href="/website/about">

and

<link rel="shortlink" href="/website/node/7" />

So if I create a new template called page--node--7.tpl.php then it works.
But if I create a new template called page--about.tpl.php it wont get picked up.

What am I doing wrong here?

Thanks!


texts: What could cause the Wysiwyg module / CKEditor randomly disappearing and coming back?

texts:
I've successfully installed and configured the Wysiwyg module with CKeditor. However, it keeps disappearing. First it disappeared when I enabled another module (cannot remember which, but thankfully it wasn't necessary so I could disable it again). I was just lucky to figure that out.

But now it disappeared again, and I don't know what happened this time. I didn't install any new modules.

Any ideas why this is happening? Is the wysiwyg module too unstable to use? If so, what's the alternative?

EDIT:

The issue keeps coming back, but I have discovered something new: if I disable a module (and optionally enable it again), apparently pretty much any module, then the wysiwyg editor appears again(!)

So it seems any change in the modules installed brings the editor back. I have only tested this in localhost, if that has anything to do with it.


texts: How to use user_load() for user on $_GET[] request in Drupal way?

texts:
I'm trying to get UID of users on $_GET[] request, following is my module code:

my_module.module

function hover_card_init() {
  $module_path = drupal_get_path('module', 'hover_card');
  drupal_add_js($module_path . '/javascripts/hover_card.js');
  drupal_add_js(array('hover_card' => array('module_path' => $module_path)), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

function hover_card_menu() {
  $items['hover-card'] = array(
    'title' => 'Hover Card',
    'page callback' => 'hover_card',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function hover_card() {
  $id = $_GET['id']; // Get UID using JS, not a Drupal way!
  $user_fields = user_load($id);

  if (isset($user_fields->name) && !empty($user_fields->name)) {
    $name = $user_fields->name;
  }

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

  return theme('hover_card_template', array('details' => $array));
}

my_module.js

(function ($) {
  Drupal.behaviors.hover_card = {
    attach: function (context, settings) {
      var module_path = Drupal.settings.hover_card.module_path;
      var hoverUserDetails = '

';
      $("a.username").hovercard({
        detailsHTML: hoverUserDetails,
        width: 250,
        onHoverIn: function () {
          var user_id = $(this).find("a").attr("href").split("/");
          var hover_details = $(".hover-details");
          $.ajax({
            url: Drupal.settings.basePath + "hover-card",
            type: 'GET',
            data: {
              id: user_id[3] // What should I do here? As this is not a clean and Drupal way :-(
            },
            beforeSend: function () {
              hover_details.empty();
              hover_details.prepend('Loading...');
            },
            success: function (data) {
              hover_details.html(data);
            },
            complete: function () {
              $('.loading-text').remove();
            }
          });
        }
      });
    }
  };
})(jQuery);


texts: How can I create a "related content" view but display it as a page with an url alias?

texts:
I have created a "related content" view but display it as a page instead of what would more traditionally be a block.

Let's say I have three content types, event, photo and speaker. Each photo and speaker node have an entity reference to an event node.

Photo ----> EVENT <---- Speaker

When I view an event node, I would like to have a link to a page that displays all of the photos that reference that event and a similar link/page to display all speakers that reference the event. I have created a view page for each of the subordinate content types (photo/speaker) that takes an event nid as an argument and displays all the nodes that reference that parent node, but there are a number of issues related to the url of these view pages which follow the structure /node/%/photos.

Aesthetically these url's are not ideal. I would prefer to have the url contain the url alias of the event node. For example /event1/photos and event2/photos etc. would all be pointing to the same view but passing the bid of the event as the argument to the view.

I am also open to the possibility that I am going about this in the wrong way so any advice would be appreciated.


texts: How to have calendar popup in a form field of 'date' type?

texts:
Using Drupal Console, I created a custom content entity in which there is a 'date' field:

$fields['subscription_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Date souscription'))
  ->setSetting('datetime_type', 'date')
  ->setDefaultValue(array(0 => array(
    'default_date_type' => 'now',
    'default_date' => 'now',
  )))

The edit-form works as supposed and, particularly, editing 'subscription_date' brings up the calendar popup:

In my custom module, I defined a table form to 'mass' edit this entity:
I defined the date field in the form this way:

$form['souscriptions'][$key]['date'] = array(
    '#type' => 'date',
    '#default_value' => $default_value,
);

In Firefox, it looks like:

and editing a date field doesn't show the date popup :-(
While in Chrome, it's OK:

Any idea why?
What should I add to my form to have at least the simple calendar popup I have in my content entity edit-form?

Forgot to say: i'm using Drupal 8.4.2


texts:
I have a Unit test where I need to print a string so I decide to use the t() function to translate it:

$this->assertTrue(is_numeric($expected), t('Parameter is numeric.'));

But the problem is that in the Unit test the t() function is not available. So I decide to check a similar Unit test in core (SortArrayTest) and the test don't translate the string:

$this->assertTrue(is_numeric($expected) && is_numeric($result), 'Parameters are numeric.');

I know that at this moment Drupal don't have integration with the Unit test from the UI, but this can be possible in future, so:

Should I translate string inside a Unit test? If the answer is Yes, How I can do it?


texts: After disabling and uninstalling memcached module, I get this PDOException and WSOD?

texts:
I´ve cloned my production site in a local Xampp installation.
My site has Memcached installed (in the server and I´ve got the drupal memcache module installed).

But I´ve got this error at my local site:

  You must enable the PECL memcached or memcache extension to use
  memcache.inc

(this is repeated at least 30 times, so that line is printed about 30 times at the top of every page).

Now, I´ve disable and unninstalled memcache at my local installation, and the error is still there.

I´ve tried after that deleting the additional settings added to my settings config file:

  $conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['cache_default_class'] = 'MemCacheDrupal';
  $conf['memcache_key_prefix'] = 'memcache_sitio';
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

But if I do eliminate those lines (after I´ve uninstalled -not only disabled- memcached module), I get WSOD and this error:

  Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc:2139
  Stack trace: #0
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(2139):
  PDOStatement->execute(Array) #1
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(664):
  DatabaseStatementBase->execute(Array, Array) #2
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(2318):
  DatabaseConnection->query('SELECT expire, ...', Array, Array) #3
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\lock.inc(167):
  db_query('SELECT expire, ...', Array) #4
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\lock.inc(146):
  lock_may_be_available('schema:runtime:...') #5
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\bootstrap.inc(405):
  lock_acquire('schema:runtime:...') #6 C:\Users\Victoria in
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc
  on line 2139

Please note that I´ve deleted all cache, tried disabling (and enabling) all performance options, and I´ve run run cron more than once.

What should I do? Thanks!


texts: Drupal 7 Site Structure - Contextual Filters & View Path

texts:
I have a Drupal 7 website that is a resort guide.

I am now going to start adding further resorts to the site but I have a query regarding the site structure and how to use Views contextual filter well.

As we speak, the domain is set out for the one resort like as follows;

www.domain.com/[node-type:resort--title:resort-1]/[node-type:parent-category--title:hotels]/node:hotel]
www.domain.com/[node-type:resort--title:resort-1]/[node-type:parent-category--title:bars]/[node:bar]
www.domain.com/[node-type:resort--title:resort-1]/[node-type:parent-category--title:restaurants]/[node:restaurant]

On the [node-type:parent-category] I use a block created through Views to display a masonry grid for each of the nodes that are tagged with that category ie a masonry display of bars

I am now wanting to use views and panels to display all the relevant information using contextual filers but because I have a node for that particular resort as the parent, I cant use a contextual filters.

So what I am adopting is setting out the new resorts as follows;

www.domain.com/resort/[views:page-contextual-filter:term:resort]/[views:page-contextual-filter:term:category]/

Is this the correct way to implement the site? Or could you suggest a better way. I have asked this a few places and got no response, remember we was all beginners like me at one point, help me out if you can.

Thank you!


texts: Trouble accessing twig variables passed from custom block

texts:
I've looked through many similar questions and can't figure out what I'm missing. I have a custom module with a block...
/**
 * Provides the 'Four Words' block
 *
 * @Block(
 *   id = "na_fourwords",
 *   admin_label = @Translation("Four Words Hero"),
 *   category = @Translation("Custom"),
 * )
 */
class NAFourWordsBlock extends BlockBase {

  public function build() {
    return [
      '#theme' => 'block__na_fourwords',
      '#myvar' => 'TESTING',
      '#attached' => ['library' => ['na_fourwords/na_fourwords']],
    ];
  }
}

In my .module file:
function na_fourwords_theme($existing, $type, $theme, $path){
  return [
    'block__na_fourwords' => [
      'variables' => [
        'myvar' => NULL,
      ],
    ],
  ];
}

In my twig, {{ myvar }} doesn't render. If I call {{ kint(elements.content) }}, I get ...
elements.content => Array
(
    [#theme] => block__na_fourwords
    [#myvar] => TESTING
    [#attached] => Array
        (
            [library] => Array
                (
                    [0] => na_fourwords/na_fourwords
                )

        )

)

It looks like the data is getting passed through ... why am I unable to access it? I feel like there's something simple I'm overlooking.
Drupal 9.1.7
PHP 7.4.16
Thanks!


texts:
I am not a coder, how can I get a route name from YAML Form (ex.Contact form) and put it to YAML Block?
Is there a route name UI like path auto UI?
thank you


texts: How to solve Mysql PDOException: SQLSTATE[42S02]: Base table or view not found:

texts:
I have created form to add general information about daily work. When I submit this form it will give me following error. Please help me. I have checked my setting.php. There prefix is drup_

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'i1164525_drup1.drup_drup_Detailstable' doesn't exist: INSERT
  INTO {drup_Detailstable} (Username, Email_Id,
  Work_Location,Team_size,Total_hours,Date,Description,Verified) VALUES
  ('admin','swap@mm.com','abc','1','20','12/12/2014','Test','Not
  Verified'); Array ( ) in eval() (line 43 of
  /home/csrdiarycom/public_html/modules/php/php.module(80) : eval()'d
  code).

 <form name="form" method="post" action=''<?php echo $_SERVER['PHP_SELF']; ?>">
 Work Location
 <input type="Text" name="location" value=""/>
 Individual/ Number of people
 <input type="Text" name="numberofpeople" value=""/>
 Date
 <input type="Text" name="date" value=""/>
 Total Time spend by You/Team(In Hours)
 <input type="Text" name="Totalhours" value=""/>
 Your Experience
 <textarea row="5" maxlength="200" cols="30%" name="comment">Type here</textarea>
 <input type="Submit" name='Submit'/></form>
 <?php
 if(isset($_POST['Submit']))
 {
   $location=$_POST['location'];
   $numberofpeople=$_POST['numberofpeople'];
   $Totalhours=$_POST['Totalhours'];
   $date=$_POST['date'];
   $comment=$_POST['comment'];
   db_query("INSERT INTO {drup_Detailstable} (Username, Email_Id, Work_Location,Team_size,Total_hours,Date,Description,Verified) VALUES ('$e','$e','$location','$numberofpeople','$Totalhours','$date','$comment','Not Verified')")->execute();
  echo "
Thank you for your Comment!
";
  }}
  ?>


texts: Node relationships, backwards or forward?

texts:
I know node references are not as popular as entity references are, but I'm curious on backwards and forward relationships.

This is a use case I see someone doing.

Job  < -- Job Application

2 content types, and the node reference in the Job application point to Job.

In reality, shouldn't Job be pointing to the Job applications?

2nd use case

Project --> Files

When you create a project, you attach files to it, most of the time files are known beforehand so additional ones after parent node creation would be unlikely.

This is the more "correct" way as I see it, a Project can "have many" files. I also notice it could be done in the reverse as well, a file could reference a project.

The whole idea of Many to one, one to many, and many to many relationships in Drupal using the node / entity references module really make me wonder.

With the project user case, you can use references dialog, and you can create children right then and there. Doing the reverse of that, creating a parent could be possible, but why would one do that?

I've watched many videos, and I can see people doing it both ways almost with no consistency. I almost get confused myself when thinking about this. I come from doing things where these relationships are a bit more defined, and the DB schema is setup as so.

So does it really matter which way you put the reference? Also is it bad to have 2 node reference each other? I noticed there is some back references modules etc, what use do these have outside of making it easier for views? Did they have provide any other practical uses? (I know views3 with the node reference module , back references work out of the box now). Does it really just come down to workflow and how it would be easiest to get the creation forms to have the experience you want?

If someone could clear this up for me, I would really appreciate it.


texts: Easy way to create blocks programmatically?

texts: Learning Drupal. I know now that I can create block through the backend, but I would rather precreate them programmatically, if it's possible. In fact I'm pretty sure that it's possible. But what's the easiest way?


texts: I am very new to Drupal. I want to add multiple content to my homepage,very simple,like this structure,I need to add two contents ,Main Content 1 and Main Content 2. I am able to add Main content 1 easily, but how can i add the main content 2 below the main content 1?. Will I be able to do it from the admin panel or I will need to change the theme structure?


texts: jQuery.browser.msie depreciated in 1.9 trying to fix in Drupal 7

texts:
The design template I am using needs jQuery 1.9. But Drupal 7 doesn't seem to support 1.9. Please correct me if I'm wrong
The issue is that when in import jQuery 1.9 in Drupal 7 then here is the following error when in admin (overlay) trying to add content:

 Uncaught TypeError: Cannot read property 'msie' of undefined

This is coming from overlay-parent.js. It has the following code:

if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {

It's causing an error because I am importing jQuery 1.9 and Drupal 7 runs code that contains the deprecated and removed jQuery.browser method.

The problem is that, after updating the code in  modules/overlay/overlay-parent.js to:

if (navigator.userAgent.match(/msie/i) && navigator.userAgent.match(/7/)) {

These changes are not taking effect. Perhaps this has to be compiled into some minimized .js file but I am not sure. How to make these changes in Drupal 7? Any alternative ways to make jQuery 1.9 compatible Drupal 7?