texts: Drupal 7 Views bulk operations based on terms

texts:
I want to do bulk operations based on terms instead of node id. For example, I have a term called "XXXX", I have selected this term for 10 contents. So, in manage views I want to display only the term name, if when user selecting that term and do publish/unpublish, that 10 contents should be publish/unpublish.

Is it possible with Rules? Can anyone please guide me?

Thanks in advance.


texts: The path_processor_outbound service only work after clearing the cache

texts:
I tried overwrite all links from my site in Drupal 8 in accordance with a URL parameter.

I use the service path_processor_outbound and implemented the processOutbound() method, extending the OutboundPathProcessorInterface interface.

services.yml

services:
   test_concept.test_concept_sayHelloService:
   class: Drupal\test_concept\Services\TestConceptRepeater
   tags:
      - { name: 'path_processor_inbound', priority: 100 }
      - { name: 'path_processor_outbound', priority: 300 }

Method of my class

public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
  $current_uri = \Drupal::request()->getRequestUri();
  $path_args = explode('/', $current_uri);
  $sede = $path_args[1];
  $path = "/" . $sede . $path;
  return $path;
}

This work very good when reloading the site alter flushing the cache, but when I change the URL parameter and reload the site again, the URLs don't change, even if processOutbound() runs again.

Is a problem with the cache?


texts: Draggable views module doesn't sort content

texts:
I wanna sort my view with Draggable Views Module , but my view display content not field.
is there any solution to sort my views ?


texts: Aggregate function with voting api / fivestar

texts:
I'm using Drupal 7, fivestar and Voting API.

I use hook_votingapi_results_alter to aggregate some results (number of votes above 80 (4 stars)) and use this in views.

I followed the api, but it does not work :

function MYMODULE_votingapi_results_alter(&$vote_results, $content_type, $content_id) {
  $sql  = "SELECT v.value_type, v.tag, COUNT(v.value) as count_4_stars ";
  $sql .= "FROM {votingapi_vote} v ";
  $sql .= "WHERE v.content_type = '%s' AND v.content_id = %d AND v.value_type = 'percent' AND v.value >= 80 ";
  $sql .= "GROUP BY v.value_type, v.tag";

  $aggregates = db_query($sql, $content_type, $content_id);

  while ($aggregate = db_fetch_array(aggregates)) {
    $vote_results[$result['tag']]['percent']['count_4_stars'] = $result['count_4_stars'];
  }
}

function MYMODULE_votingapi_metadata_alter(&$data) {
  $data['functions']['count_4_stars'] = array(
    'name' => t('4 stars'),
    'description' => t('4 stars'),
    'module' => 'mymodule',
  );
}

Do you know from where comes the problem?


texts:
My cache_page table fills up immensely. I see that the expiry field has values = -1. I assume that means it never expires. Which could be why the table fills up so much.

I wrote a hack to get around this, but would really like to know why this is happening so I can fix the root cause instead of adding a hack?


texts: Field difference plugin for referenced entities

texts:
We have a way to see diff for field changes/revision on paragraphs hosted on any entity, however does not look like we have similar functionality for Referenced Media Entities.
Paragraph module seems to provide Field Diff plugin, ER field provide a similar plugin which allows to compare of Label or ID but not on fields.
Just wanted to check if I am missing any configuration or it requires extending the ER plugin to show field diff.


texts: How to add custom predefined content panes?

texts:
I've seen in a few tutorials and videos online that the following Content Panes are available:

Those that say Add links, add file, etc. For example this video also shows one called 'add page banner'. However, I don't fine how to install those content panes!

I've installed the Panels module, In-Place Editor, CTools and Custom Content Panes among others, but those are not available. How can install them? (using Drupal 7) Thanks.


texts: Get rid of classes from views root container

texts:
Looking for a way to clear all unnecessary in terms of semantic classes from top-level div for a view:

        ROWS

want to become:

        ROWS

I have tried Semantic Views and Fences but they all deal only with view content (field or rows) but not with the top-level div config.

I know that some bits can be changed with views-view.tpl.php however you can only clear all classes from it but I want to use css class from Views configuration.


texts: Views Filter 2 Content types but with condition on one of them

texts:
I looked up this one before posting: Views filter criteria multiple content types (Drupal 7)

And even though the problem is the same, the solutions provided do not seem to work.

I have Content Types A and B. B has a boolean field.

I need to filter and display all As and Bs if boolean is true.

My filter setup looks like this:

Content : Published AND
Content Type : A

OR

Content : Published AND
Content Type : B AND
Boolean Field : True

The Query that gets produced is the following:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created
FROM `node`
INNER JOIN `field_data_field_boolean` ON node.nid = field_data_field_boolean.entity_id
  AND (field_data_field_boolean.entity_type = 'node'
  AND field_data_field_boolean.deleted = '0')
WHERE (( (node.status = '1')
  AND (node.type IN  ('poll')) )OR( (node.status = '1') AND (node.type IN  ('webform'))
  AND (field_data_field_boolean.field_boolean_value = '1') ))
ORDER BY node_created DESC

The problem is that Inner Join that gets produced instead of a Left Join for instance.

Which setup would allow me to perform the required filtering?

EDIT: Seems it's a know bug. Related links:
http://drupal.org/node/1766338
Changing an inner join to a left join in views 3.3?


texts:
I have a form alter handler like this.

function toyotaec_form_webform_client_form_seleccionar_alter(&$form, &$form_state) {
    $concesionarias = concesionarias();

    $form['actions']['submit']['#value'] = 'Enviar';
    $form['submitted']['concesionaria']['#options'] = $concesionarias;
    $form['#validate'][] = 'toyotaec_form_webform_client_form_seleccionar_validate';
    $form['#submit'][] = 'toyotaec_form_webform_client_form_seleccionar_submit';
}

Actually, this code is not a hook_form_alter but a function called by the actual hook. The hook calls this function passing &$form and &$form_state also by reference.

After this, I have the corresponding handlers. Both handlers are called as expected. The handler I want to focus in is as follows:

function toyotaec_form_webform_client_form_seleccionar_submit(&$form, &$form_state) {
    $values = $form_state['values']['submitted_tree'];
    $input = &$form['submitted'];

    $concesionaria = trim($values['concesionaria']);
    $redirigir = trim($values['redirigir']);
    $modelo = trim($values['modelo']);

    //obtenemos cual es la concesionaria (por marca, descartamos las ciudades)
    $mconcesionaria = current(explode('-', $concesionaria));

    //las redirecciones diferidas van a tener una salvada incluyendo la url.
    //las redirecciones directas no van a tener salvada.
    $form_state['values']['submitted']['3'] = _redirect_bystore($mconcesionaria, $redirigir, $form_state, $concesionaria, $modelo);
}

For the last line, I also tried assigning $form_state['values']['submitted_tree']['url']. This url field is the 3rd field and I have to keep track of it, but even when the data is stored in the array (confirmed by using dpm() on it), the form result has a blank url field.

For this, I'm using Webforms in Drupal 7.

My question is: how can I alter the submitted data? It seems that - for the submit handler - form state is not passed by reference.


texts: How to modify the display of custom line items in the ADD To Cart Form?

texts:
My issue is this, imagine that I have created a few custom line item types in Drupal Commerce called:

Text on TShirt FRONT
Text on TShirt BACK

I use these two fields in the ADD To Cart Form checkbox so that the customer can specify what the want on the fron of the Tshirt to say and the back. So far so good.

The issue is that how do I change the display of this product node so for example I don't want it to appear in a single column but in two columns side by side.

I have tried Panels, I have tried Display Suite, this is not working. I can't even change the order of fields say I wanted the back to show up first and then the front.

I have tried changing things around in line item configuration display, which doesn't work and I have also tried changing the disply of the product display content type, (which btw does not even show the individual fields of the add to cart forms).

I am not good with coding so I would appreciate if I can work on this from the front end with any modules.


texts: Add specific CSS class with Semantic Views

texts:
I am searching for days now and don't find the solution so I exposed my problem here.

I am under Drupal 7 and I don't find an issue for this problem.

Here is the purpose:
I created content with one specific field, a boolean, so when it's checked i want to add a class to an existing view. I explain....
Once I created content explained before, I create a view for it (with semantic views) and save!
It works perfectly but....what I want to do is that when I check the boolean (in the content) it adds me a new class to the article () see figure below:

In a content (created with a custom content type), I check this checkbox:

And so:

became:

From now the source code looks like this:

Thank you very much for your answers!


texts: How to fetch data from already saved nodes to the edit-form for node creation?

texts:
I have this scenario: a content-type A (event) has an entity-reference to another content-type B (location). Now, if an editor adds a new event and enters the (already existing) location by "autocomplete" or dropdown-list, i want to display all other events referenced to that location in the edit form to prevent dups (and redundant work).

I imagine this like a "check colliding events for this location"-button, that is triggering a view perhaps, but it has to be "before" saving the new node.

I already tried a bit with Rules-module, but there's probably no way to trigger this, though the rules-event "before saving new content" is just one step to late, because all the work is already done and all fields are filled...

Is there an approach on module-level for this or do i have to dive into modifying hook_form_alter?

Can someone point me in the right direction?
Thanks a lot in advance.

(Drupal 7.14, Views 7.x-3.3+122-dev, Calendar 7.x-3.3+0-dev, Date 7.x-2.5+8-dev, BEF, Address Field 7.x-1.0-beta2)

Update: So far i achieved an approach with a combination of Views and Panels. I override the standard "Node add/edit form" with a panel for my content-type A. To show the nodes of Content-Type B i added a view to that panel. They are shown in a two-column layout.

This works until i bring the "check" into the game. I added an exposed filter to the view, but when i use it, the node form is submitted instead of showing the filtered view.

I opened another question on this issue: Exposed filter of a view embedded in a panel overriding a node form triggers node submission. How to prevent this?

Question: Am I totally wrong with this approach (Panel with View and Form)?

Is it possible to have a custom form with the exposed filter "before" the node form to use the results of the filter to show the view?

I'm lost a bit...

Any help highly appreciated...


texts: Using regex in Twig replacement patterns in Views

texts:
I am trying to output a field as a custom link using the rewrite configuration with Twig replacement patterns in Drupal 8 Views, as depicted in the screenshot below.

Views field: (W)here is New York?
Desired output: example.com/posts/where-is-new-york

In the Views field configuration, I have selected:

Rewrite results: Output this field as a custom link

and entered a few different regex patterns, to no avail. The result I get is always:

example.com/posts/%28w%29here%20is%20new%20york

Is there a third-party plugin for PCRE-style regex filters for Drupal 8? Or is this something that must be handled in a template file, i.e. views-view-field.html.twig?


texts:
I have configured my node using Fivestar module such that user can vote on multiple parameters. For ex. The type of node is movie and user can vote the node based on Script, Acting, Story, Direction, Cinematography. All of this works fine and I am also able to calculate an average of all the fields using 'Computed Field'.

Now how can I make a user vote on all items in a group and not just individual ones in Drupal 7 ?


texts:
As this is the first time using rules for me, maybe I am doing something wrong. I want to set the product price to 0 if no price is set. What I am doing so far is this:

Event is "before saving a commerce product"
Condition is "Data value is empty"
Action is "Set a data value"

But there is just nothing happening and I still get an "no price set error" when I try to save a product without a price. Anyone knows how to do it right?


texts:
almost every time I delete a field in my product types I get this message popping up in my dashboard :

ENTITY/FIELD DEFINITIONS Mismatched entity and/or field definitions
The following changes were detected in the entity type and field
definitions. Product The commerce_product.field_produit_labels field
needs to be updated.

It has not been possible to update entities with "Drush" for some time.
Why do I have these problems regularly ? This is only with the Commerce module.
How can I correct this? Without breaking my site.
ubuntu@ov-b2b650 ~/www-example-com $ drush entup

In UpdateDBCommands.php line 110:

  Drupal removed its automatic entity-updates API in 8.7. See https://www.drupal.org/node/3034742.

entity:updates [--cache-clear [CACHE-CLEAR]] [--no-cache-clear] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--druplicon] [--xh-link XH-LINK] [--notify] [--] <command>


texts: Taxonomy Terms node count of different content type along with zero count in a hierarchy

texts:
After much headache I was able to maintain a kind of hierarchy for the taxonomy terms, of the already continuing issue here, please click the below link

Taxonomy Terms node count of different content type

I did It like this, but still needs to do more.

In second step select the parent relation and check the exclude display.

Under format option select the parent taxonomy under group 1

I am getting the parent category under  tag and the child terms as list-terms. using jquery I can display it in an accordion style somehow.

Now the problem i am facing is that empty taxonomy terms with counter zero are not getting displayed, please help if anyone knows the solution.


texts: Render database values using 'markup tags' other than 'table tags'

texts:
to keep things simple, I am trying to load a specific set of values from a database, which using the following code works:

foreach ( database::load() as $bdt) {
  $row[] = (array) $bdt;
}

$content['table'] = array(
  '#type' => 'table',
  '#rows' => $row,
  '#empty' => t('No entries available.'),
);

Which produces the following:

                  5.00 PM

                  1:00 PM

                  1:00 PM

                  3:00 PM

                  3:00 PM

                  5:00 PM

But I don't want to use table formats and I want to use other html markup tags, such as "
" or "
". I have tried to change the '#type' => 'table' to '#markup' but it will not render anything.

$content['table'] = array('#markup => '
time ' . $row '
',);

I have searched a few sites about it, but all point information back to using table format.

The working code was extracted from the "example modules" using the DBTNG example.

Please can anyone tell me how to go about it?

Many Thanks


texts: How do I synchronize 2 sites, one installed with Composer and one from downloaded zip?

texts:
I have two sites:
one, local, installed with composer create-project drupal-composer/drupal-project:8.x-dev mysitelocal --stability dev --no-interaction
another one, remote, installed from drupal-8.7.6.zip that has been downloaded from drupal.org, the files in the archive have been copied to remote location and then myremotesite/core/install.php has been executed.

Of course, folders structure is different in the two locations.
My question is: how to sync from my local to my remote site?


texts: I added sort criteria by price to my catalog view, and in the sort criteria I have only to option to use by default one of them - Ascending or Descending. But I don't want to use any sorting by price by default in catalog, I would like to apply it (one of the option Ascending or Descending) only after user chose an option and pressed button 'Apply' on the sort form. Is there any opportunity to do that?


texts: when to use include (inc) files in module development

texts:
I think I understand the structural differences of a .inc file (compared to a .module), but could someone describe the design differences?  I see drupal example modules calling an .inc file with hook_menu, or I see call .inc file for function defintions.

Under what circumstances does one put code in a .inc file?  Any general design guidlines that some adhere to?
Is there any advantage other than clarity as to why one would use an (or multiple) .inc file? performance? versioning?

thanks!


texts: Why isn't the image added in the block settings shown in the front end?

texts:
When I try to add a background image in Bootstrap block settings (the settings added by the BB Animation Module) Drupal uploads it, but the image doesn't appear on the front end.

Any help about this?


texts: Null value in DB displays content on page

texts:
I have a blank category box on the bottom of the following page (http://www.suncorstainless.com/stainless-steel-hardware) and it appears that it's caused by a Null value in a table somewhere in my DB. I'm not the developer of this website and am having a hard time determining where this issue is in the DB.

Are there any tools available to determine the DB table that is displaying content on a page?

Thanks-in-Advance


texts: How do I organize webforms in admin panel

texts:
I want to customize the Webforms Admin view.
Place all the related webforms in a groups and control who can access the groups.

For example I have many departments. I create a group to each department and allow group members to access  the webforms and not other departments.

Can anybody direct me how to achieve this?


texts: How to make form_alter act upon boolean choice rather select list

texts:
I am working on a form_alter() based on Form API states which is about switching a field choice based on the value of a select field as below;

'select[name="field_date_type"]' => ['value' => 'allday']

I would like to know what syntax is required for changing the field widget from select to boolean or checkboxes or radios.

I have tried switching select to boolean, checkbox and radio but none are working for me.

What am I doing wrong?


texts:
I've been trying to use hook_field_access to deny access to fields under a certain bundle. However it does not work as intended.

This is the code

function applx_field_access($op, $field, $entity_type, $entity, $account){
    return FALSE;
}

All the examples work somewhat like this, but im not sure what is wrong here.


texts: How to set canonical urls to migrated data

texts:
I have a new site, to which all the articles from my four old sites are migrated. Now in a search engine,if anyone searches and clicks on any article's link it should redirect to the same article in the new site.

How can a get this in Drupal?

Please tell me about canonical url of nodewords module?


texts:
I'm on Drupal 8. I have created a new media bundle (permissions_json) which can be created from /media/add/permissions_json, where administrator user can upload specifically formatted JSON files, and I can upload to it all fine and dandy.
I'd like to validate the file uploaded and rename it. The problem is that I can't find a way to hook into the form. Implementing hook_form_FORM_ID_alter() with gp_mcs_media_permissions_json_add_form_alter() or gp_mcs_form_media_permissions_json_add_form_alter() doesn't have any effect. Even the following implementation didn't have any effect.
function gp_mcs_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
}

If I put a simple exit() on the module's page stops the website, so the file is accessible. I just can't figure out how to add validation to this add media form.
How can I alter the form to add a new validation handler?


texts:
I have several custom modules and each one of them serves different functionalities. Each module contains from few to many hook implementations and inevitably there are cases where I have to use a hook more than one times between the modules, hook_menu for example.
What are the downsides (if any) of using the same hooks more than one times in different modules ? Is that recommended ? What about performance?
Thanks!


texts: Where can I set cardinality for a custom field?

texts:
I have a custom field defined in a module I am writing, which works correctly. The default cardinality is unlimited and I want to limit it to 1.
I am sure I need to call setCardinality(FieldStorageDefinitionInterface::1) somewhere, but I can't understand where exactly I should add that call.


texts: Views Fields and Relationship with Aggregation

texts:
I have three content types :
Content type A (= leg)
Content type B (= transport)
Content type C (= ticket)

B has a node reference to A.
C has a node reference to B.

I have a views list with the following and aggregation setting is on;

    FIELDS
    Content: Nid
    Content: From
    Content: To
    (field_transport) MIN(Content: Price) (for)
    (term from field_transport_type) Taxonomy term: Name (by)

    FILTER CRITERIA
    Content: Published (Yes)
    Content: Type (= Leg)
    Content: From (exposed)
    Content: To (exposed)

    SORT CRITERIA
    Content: Post date (desc)

    RELATIONSHIP
    (field_transport) Content: Leg (field_leg) - reverse
    (field_leg) Content: Transport (field_transport) - reverse
    (field_leg) Content: Transport Type
    (term from field_transport_type) Taxonomy term: Content using Transport Type

The result with 3 records is shown as below :

    RESULT
    How to go from Bangkok to Singapore:
    for $150.00
    by Plane

    How to go from Bangkok to Singapore:
    for $200.00
    by Train

    How to go from Bangkok to Singapore:
    for $80.00
    by Bus

I want the result with the only last line ( for $80.00 by Bus ). The result is correct before I have no relationship with term from field_transport_type.
How can I do that with aggregation setting MIN which I already applied in the field list?
I'm using drupal 7.10.

[Edit]
Here is the screen cast of my view :

Another thing is that the content type B (=transport) has a taxonomy term field (=transport type) which needs to be displayed in the field list. You can see them in the result - by Bus, by Plane, etc.

To be more clear, I attached another screen cast of my results :

The result should be 2 records above. The last three lines is the group of a leg ( Bangkok to Singpore ). This cannot be done by changing the pager settings. Pager is 10 for the page, meaning - latest 10 legs with cheapest tickets.

[Edit]
When I changed field_transport_type in FIELDS into COUNT(DISTINCT Taxonomy term: Name),
I got the result with the first two lines, but I lost the transport type names.

    How to go from New York to London: for $120.00 by 1
    How to go from Bangkok to Singapore: for $80.00 by 3


texts: Why do my files get lost when migrating a CCK Filefield?

texts:
I'm just getting stuck in to migrating D6 to D7 (please note: migrating, NOT upgrading). I'm using the Drupal-to-Drupal data migration module and its UI to define what I need to bring across.

One of the content types is "Issue": an issue of an online publication which just has a title, some body text (optional) and a file attachment for the PDF version of the publication.

To prepare the migration, I set up a corresponding content type in the D7 database, making sure that the field name was the same in D6 and in D7.

I have run a migration reasonably successfully (except for the major issue of Book structure which doesn't get handled), and all the "Issue" content has come across. However, none of the files in the "File Field" fields have been copied across. I'm trying to get my head round this: do I need to extend the Node Migration class, and if so how do I go about this?


texts: How to detect the newness of messages created with the Message module?

texts:
I have created messages to notify users that they have been tagged in a picture or that someone commented after them on a thread; pretty much like facebook-style notifications.

How could I detect if a message targeting a user is new to him?

I had two ideas:

compare the timestamp of when the message has been created and the
session timestamp. The session timestamp is refreshed every time a session requests a new
page so I don't know if I can catch the previous value of this timestamp?
catch the same event that triggers drupal_set_message().

Would there be any other method to do that?

A recent post "This is a New Message/You have 4 New Messages" has been submitted in the issue queue of the Message module but apparently, it doesn't contain any built-in function to see if the message is new.


texts:
I'm trying to use Views PHP filter feature to remove rows which don't contain some data (I can't just use "Hide if empty" feature, because the module returns a string even if there is no real value.

I'm using this string for a filter, however, if doesn't work - instead of filtering, view returns all values.

return isset($data->_field_data['nid']['entity']->field_poloha_obce_pol[und][0][geometry]);

I tried to inspire myself from some of the similar issues here, but it seems to me, that everything should be correct.

I also tested this exact code as PHP field and it returns expected value.


texts: Reordering not working for multiple values of a field in draggable views

texts:
I have a requirement in my project, reordering of draggable view items and after reordering and saving, the top row of the views should be transfered or carried to the next page.

Unfortunately i cannot do this because the view items are multiple values of a field which is a delta field. Please help me in this issue.

Any help will be appreciated!!


texts:
I have looked for days and cannot find an example of what I need to do. I wish to reformat the HTML output ckeditor uses for blockquote.

CKEditor output for quote:

Content

I wish it to output to something like:

Content

If I am able to do this, it has a lot of potential uses for every format provided in many sites for me. Does anyone know how to do this?

*Edit: My preference is to do this in PHP within a module if possible rather than JavaScript.


texts:
My case is simple: When user switches tabs, I want to dynamically fill empty fields in the tab he entered, calculating them from the tab he went from. Like suggesting city by zip code, or address by company name if I have it in database.

Problem is - I can do it on button click or on field's blur, but I'd prefer it to happen on vertical tab switch. Items with vertical_tabs type simply does not have #ajax property. Is there any neat way around it?

#states seemed a solution, but it seems they only support static value set, like:

':input[name="foo"]' => array('value' => 'bar'),


texts: How can I create a view on a profile page that shows content related to the user we are viewing

texts:
I have a specific "sport user id" that the user provides in order to grab sports results about that user. I want to display their results, which I keep updated and organized programmatically in a cron job, on their profile. The way I would like to link the content would be by keeping the "sport user id" as a field in the result content type and also as a field in the user.

How do I go about creating a filter to do this?


texts: Does rules take advantage of search api for fetching nodes?

texts:
I have a few rules which fetch nodes.

I wonder if performance would increase by creating a proper index.


texts: Associate webform submissions with the user created

texts:
I am allowing anonymous user create submissions, and creating a user programmatically based on these submissions. How do I associate this submission with the user I've just created?

UPDATE: I thought I could use db_update for this but I'd be interested to know if there is a more functional way.


texts: passing argument from one view to another view

texts: I have created two views , View1 has a list of city names (drop down select box) and View2 displays all the pharma shops across multiple cities. What i am trying to do is , when a city is choosen from view1 i need to display only the pharma shops in that city using view2. I am using drupal 7 and have no knowledge on php. Is there a way to achieve this without doing any coding? Any help would be highly appreciated.


texts: How to get formatted date string from a DateTimeItem object

texts:
I have a standard Drupal date field 'My date' (field_my_date). I can get its value:

$node->field_my_date->value  // returns: "2017-12-14T08:00:00"

But I want to get a formatted date string, which should look like: "14.12.2017".

If I analyse the field in the interactive shell (drush core-cli), then I see, that I can get the DateTimeFieldItemList object or DateTimeItem object:

>>> $node->field_my_date
=> Drupal\datetime\Plugin\Field\FieldType\DateTimeFieldItemList {#8836
 0: Drupal\datetime\Plugin\Field\FieldType\DateTimeItem {#8841},
}

>>> $node->field_my_date[0]
=> Drupal\datetime\Plugin\Field\FieldType\DateTimeItem {#8841
 value: [
   "value" => "2017-12-14T08:00:00",
 ],
}

But I have not found any method to reformat the date string. Is there some possibility to define the format of the output date string? Or do I have to reformat the output string e.g. like this:

date("j.n.Y", strtotime($node->field_my_date->value));


texts: use an inline javascript function (not jquery) on drupal 7

texts:
This is how jQuery is included in d7

(function ($) {
  // jquey codes here
})(jQuery);

How i can include javascript code (not jquery) in d7?


texts: What is the difference between Pantheon DROPS and vanilla Drupal?

texts: Is it just the added config wrappers, or is the Drupal site code itself changed? Are there any changes to Drupal module and filesystem compatibility compared to a more traditional Drupal hosting environment?


texts: Multiple File Uploads fail when webform is placed in a block

texts:
I'm in Internet Explorer support hell.

I have a webform which uses Multiple File Uploads. When the form is displayed as a regular node (e.g. www.example.com/node/4), file uploads work as expected.

When the node is shown as a block on another node, file uploads fail with the message:

  An unrecoverable error occurred. The uploaded file likely
  exceeded the maximum file size (20 MB) that this server supports.

Needless to say, all php.ini configuration options are in order, (post_max_size=128M, upload_max_size=20M, etc) and the temp folder is writable.

Uploads fail specifically on Internet Explorer 8 and 9. There is no indication in the log of anything going wrong, just the error message above.

Any ideas?


texts:
I'm still learning Drupal, and I was trying to use hook_form_alter() to resize a text field added from a module.  My problem is that I don't think I'm indentifying the element correctly.

Here's the element code:

<input type="text" class="form-text form-autocomplete" value="" size="60" id="edit-2" name="2" maxlength="128" autocomplete="OFF">

Here's my module code:

/**
 * Implements hook_form_alter().
 */
if ($form_id == 'edit-2') {
  $form['text'] = array(
    '#type' => 'text',
    '#size' => 25,
  );
}

I'm not sure what to do; any suggestions would be helpful.

Thanks!


texts:
When using the Services API with a PUT request, it returns an error saying that the signature is invalid. When working with POST I was getting access denied because the bundle was specified but this seems to be completely different.

401 Unauthorized : Invalid signature 21
["Invalid signature"]

For testing purposes, "Cache pages for anonymous users" and "Cache blocks" are both unchecked. I cleared the cache once to make sure it wasn't that.

It appears to be that the server generated signature does not match, but I saw the answer below, and the two signatures are completely different, not just missing a plus sign. I was able to log the signatures that the server sees to the devel debug log.

Service request with OAuth (Invalid signature error)

One thing I noticed which I wasn't sure about is that the base string that got logged for the request on the server started with GET, but this is a PUT request. Is that normal or could that be a bug in the implementation? My Oauth client is using PUT as the method.

Update: In looking into it, that does indeed seem to be the problem or at least part of it.

if($_SERVER['REQUEST_URI'] == '/api/rest/resource/18.json'){
    die('hi put' . $_SERVER['REQUEST_METHOD']);
}

The above code inserted at the beginning of index.php gives me hi putGET. However POST works perfectly fine.

My access log has this line

"PUT /api/rest/resource/21.json HTTP/1.1" 401 21 "empty referrer" "My User Agent String"


texts: Translate blocks in page_manager variant

texts:
I am building a multilingual Drupal site.  My 'static' pages are built using the page_manager module.  I am using the core multilingual modules and the Translation Manager Tool.  With these I can translate my custom entities / block / blog posts and the like.

The problem I am having is that I cannot translate the content of the blocks I have placed in my page_manger variants.  If I load them up in the translation management tools only the Label of the page is available for translation, not any of the 'content' of the page.

I can see that I can create a new variant that is selected based on the current language, but this means I need to recreate each of the page layouts.

What I would like to do is have a single page variant but translate the content of the blocks in them in the same way that I would translate an entity or a custom block.

I cannot find a way to do this, is this possible?


texts: Drupal 6: Menu and taxonomy name mismatch

texts:
The error log on my drupal 6 site displays the message "Menu and taxonomy name mismatch: Gerona (42) != Gerona (7)"
I looked it up and apparantely it is a taxonomy menu - i18n problem, they don't get along... does anyone know how to solve this?

Thanks


texts: How make patch in PHPStorm suitable for Drupal.org?

texts:
PHPStorm will create patch in this form:

Index: core/modules/node/templates/node-edit-form.html.twig
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- core/modules/node/templates/node-edit-form.html.twig    (revision 4652b443e9f89734487e225fb76829595b5239a1)
+++ core/modules/node/templates/node-edit-form.html.twig    (revision )
@@ -1,6 +1,8 @@
 {#
 /**
  * @file
+ * Default theme implementation for a node edit form.
+ *
  * Two column template for the node add/edit form.
  *
  * This template will be used when a node edit form specifies 'node_edit_form'

After I export it I always have to remove the header and add the a/.. and b/.. prefixes and convert to LF so it'll look like this:

--- a/core/modules/node/templates/node-edit-form.html.twig
+++ b/core/modules/node/templates/node-edit-form.html.twig
@@ -1,6 +1,8 @@
 {#
 /**
  * @file
+ * Default theme implementation for a node edit form.
+ *
  * Two column template for the node add/edit form.
  *
  * This template will be used when a node edit form specifies 'node_edit_form'

Is there a way to export patch that I can directly use for drupal.org?


texts: Loading module-related files only on certain pages

texts:
I installed the Chosen module and it is conflicting with my JavaScript code. That module gets loaded on every page, even if there is no select box on the page. It is definitely unnecessary to load the files from that module when they are not necessary at all.

What I want to do is modifying the module to only load on certain pages.

How should I go about doing this? What function do I have to call or look for within that module?


texts: how to set custom permission to custom menu access?

texts: I  am trying to create student management system in which i have been created custom 'registration form', for registering to website then i have created 'list of registered students' menu to show registered students.I want to set permissions such that admin can edit registration form and authenticated user can only see 'registration form',admin can see list of registered students but authenticated user can not see that list.So please guide me to do so.


texts:
I need to rename the node home-care/vids into home-care/product-solutions. The trouble is that I can't find home-care/vids in the dashboard of this relatively big site.

How can I find it?

I have even done a MySQL database search but results are not helpful for me.


texts: Can 'terms' be shared across 'vocabularies'?

texts:
I think I might have a fundamental misunderstanding of how taxonomy works in Drupal.

I've set up some vocabularies, such as 'accommodation', 'things to do' and 'eating out'. Within those, I've added parent terms 'accommodation types' and 'ratings' for accommodation, 'nationality' and 'suitable for' for eating out and so on.

Both vocabularies share some common features, though, such as 'location'. I set up 'location' within the 'accommodation' vocabulary first and then tried to make it available to 'eating out' by setting it as a parent, but I could only see other terms within the vocabulary.

What is the best way for me to allow each vocabulary to share a location without manually recreating and updating a 'location' term in each vocabulary (which surely must be the incorrect way of doing what I'm trying to achieve?)?


texts:
I wrote my first module which happens to be in Drupal 7. The module uses hook_menu to correlate URLs with three custom-coded, page call backs. These callback functions that construct the custom html are currently inside the .module file.

The file is getting a little long and I would like to put the three custom-coded page call backs into another file. My first attempt did not work this morning, I'm not sure what I did wrong...

1) Added this line to the .info file:

files[] = my_module.pages.inc

2) Placed the callbacks into my_module.pages.inc

What is wrong or missing in this approach?


texts:
I'm using the Charts module to create a chart in my view (using its Views integration). But the supported chart type doesn't include Radar chart, which is what I would want it to be.

I found a sample of such chart at https://www.drupal.org/files/RadarGraph.png, which looks like so:

Is there a way I can get that to work?


texts: How to conditionally load javascript file on view page

texts:
I'm trying to load some theme javascript only to one view(multiple displays). I've tried to use the views preprocessor funciton, but maybe I'm doing it wrong:

function themename_preprocess_views_view__viewname__page(&$variables){
  this doesn't run on view page;
}

I've also tried it with the function name themename_views_view(). There's not much documentation on this.


texts: Can't update core with composer: "Your requirements could not be resolved to an installable set of packages"

texts:
I am not able to perform a security upgrade of Drupal core with composer.  I get "requirements could not be resolved."  Here is my composer.json:
https://pastebin.com/KxEQdPkt

Here is the response:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for symfony/psr-http-message-bridge v0.2 -> satisfiable by symfony/psr-http-message-bridge[v0.2].
    - drupal/core 8.3.2 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.3 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.4.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - Conclusion: don't install symfony/psr-http-message-bridge 1.0.x-dev
    - Installation request for drupal/core ^8.3.2 -> satisfiable by drupal/core[8.3.2, 8.3.3, 8.3.x-dev, 8.4.x-dev].


texts:
How can i check which radio button has been checked from a list of radio buttons ? Is there any key in the form array which holds the checked radio ?

I am using an ajax call for a bunch of radios buttons and i would like to do some "checking"  only if the right radio button was selected.

As an alternative , how can i append the "#ajax" parameter to only one radio button in a list of radio buttons ?


texts: Why is Rules reacting on Commerce Events multiple times and out of order?

texts:
I am having lots of problems with my site because Rules is evaluating Events multiple times, and out of order.

For example, the debug log shows that when I add a product to cart, Rules reacts as follows:

Calculating the sell price of a product <- for internal processing, ok.
Calculating the sell price of a product <- why twice?
Before saving a commerce line item
Apply a fee to a given order <- why now?
After updating an existing commerce order <- but it didn't update; no fee added?
After adding a product to the cart
Calculating the sell price of a product <- for display, ok.
Apply a fee to a given order <- why now? and why again?
Select available payment methods for an order <- why now?

Would like to know if there is a way to debug deeper than the log; i.e. find out exactly when each rule evaluation was called ...

Somebody please help, this is making it impossible to work!

thank you.


texts: Adjust weight for menu items in different languages

texts:
My site will be in English and Arabic. English reads from left to right and Arabic from right to left. Drupal 8 works great with this if you enable all 4 multilingual extentions.

The only problem I have is that I translated the main menu, but I can't find how I can add a different weight to the separate menu items, this since I want the menu to be mirrored on Arabic.

If you go to the separate menu items you can add a weight but above it it is written: Weight (all languages)

How can I adjust the weight per language per item?

UPDATE: the answer by Owais Alam does not handle the adjustment of menu-items-weight per language in Drupal 8


texts: Display alternate content after webform submission

texts:
Is there a way to display an alternate content once user submits a webform?

For example user submits "Email Sign Up" form on the homepage, and the next time they visit the page containing that form they would see a different message.

Thanks!


texts: Advantages of using drupal mobile technology over mobile middlewares

texts: This is a very serious question that every one asks. I have a drupal website now which is not mobile ready. I will tell the scenario. We gave a demo to client of kurogo, which we modified to show content from drupal website. So 1st question was, whats the benefit of this over creating mobile ready themes with in drupal. So my question is, will there be any extra benefit of using external mobile middle ware like Kurogo, then developing drupal mobile themes.


texts: How to get all pages of a custom content type to be displayed using a custom view?

texts: In Drupal 8, how can I get all pages of a custom content type "MyPage" to be displayed using a custom view "MyView"?


texts: How can I make Search Terms in a View to look fo into the edited Summary?

texts: I have a View of a type of content, and it has a Search Terms contextual filter. It searches perfectly (after indexing the content and running cron), but when I have a node which has the summary edited (not the default trimmed body text), the search does not return any result. How can I include the edited version of the Summary in the search?


texts:
I created a field for users using the Profile 2 module with machine name "field_user_country"

I created a block on my user profile page and i need to dynamically display the country of the currently viewed profile.

I have tried various tokens and they do not work.

What token can I use to get the country of the currently viewed user profile?

Thank you.


texts:
Hey I have added the following libraries:

my-google-maps:
  js:
    https://maps.googleapis.com/maps/api/js?key=my_funkey_key&: {type: external, weight: -400, attributes: {defer: true,async: true}}
my_other_lib:
  header: true
  js:
    js/mylib.js: { }
  dependencies:
    - core/drupal
    - core/drupalSettings

I have tried multiple ways to attach these files in a specific order(first google and then my custom js:

{{ attach_library('my_module/my-google-maps') }}
{{ attach_library('my_module/my_other_lib') }}

If it is not in the specific order the map is undefined.How can I specific the load order?


texts:
I have a content type called Pets, which only has title and description. In Pets there are only 3 data (set by Admin) Cats, Dogs and Mouse. User can select only from these data and cannot add more Pets.

After the Girls register in the site they can hit the checkbox to select the pets they have in their profile.

However, I want to have a Views table where I want to list the Girls' profile like: (that's the table I wanted to make)

Name ------ Age -------- Dogs ---------- Cats ----------- Mouse
Tina ----------- 21 ------------ Yes ---------------- No ----------------- No
Lita ----------- 27 ------------- No ---------------- Yes ----------------- Yes

When I add Pets title in the views it just shows as:

Title
Dogs
Cats
Mouse

but I want to change the fields(dogs, cats, mouse) as Columns and have Yes or No in the rows. I just tried Views Flipped Tables Module but wasn't able to do with it. any suggestions please ?


texts: 'unexpected error' when visiting any page the first time, but not the second

texts:
Quite suddenly, my site has begun behaving erratically. No matter whether the page is an admin page, or a page using my custom theme I receive the 'unexpected error' page whenever I visit the page for the first time. Strangely when I visit it the second it time it appears just fine. The error log within Drupal does not display any corresponding errors, however I do see errors in my nginx log. Here is an example error that appears

  #1 /var/www/(my domain)/http/web/core/lib/Drupal/Core/Database/Database.php(376):
  Drupal\Core\Database\Driver\mysql\Connection::open(Array)

  #2 /var/www/(my domain)/http/web/core/lib/Drupal/Core/Database/Database.php(166):
  Drupal\Core\Database\Database::openConnection('default', 'default')

  #3 [internal function]: Drupal\Core\Database\Database::getConnection('default')

  #4 /var/www/(my domain)/http/web/core/lib/Drupal/Component/DependencyInjection/PhpArrayContainer.php(79):
  call_user_func_array('Drupal\Core\Dat...', Array)

  #5 /var/www/(my domain)g/http/web/core/lib/Drupal/Component/DependencyInjection/Container.php(177):
  Drup" while reading response header from upstream, client: (my ip)
  server: (my domain), request: "GET /admin/reports/dblog HTTP/1.1",
  upstream: "fastcgi://unix/php-fpm.sock:" host: "(my domain)",
  referrer: "https://(my domain)/admin/reports/status"

I've tested the connection to my sql server and have had no issues. I've reverted to previous commits that I know worked in case the code for my custom themes and modules caused an issue. But I feel like that wouldn't be the cause if it's happening to admin pages as well. I have not done anything like a composer update or install, all the files outside my custom theme and modules shouldn't have changed.

Do the error messages point to any culprit? Is this specifically an issue with my Drupal site?

UPDATE: It occurred to me that it's possible that it's only working the second time because grabbing something cached. So there's a possibility that it's not working at all.


texts:
I just wanted to see if anyone could offer some thoughts or opinions on an issue we are having.

We are running Drupal 8 multisite via Aegir. We have a production environment and an identical testing environment set up. In our test environment we have our Drupal 8 multisite using domains such as site1-testing.com.

The issue is the file structure is set like /sites/site1-testing.com/files/. This poses an issue when we migrate to our production domain which would be site1.com. Anywhere where we inserted a link to a file would still be referencing /sites/site1-testing.com/files/filename.pdf, which would of course, cause all of our production links to break.

We use linkit as well to insert the files into nodes. I've tried using pathauto, pathologic in conjunction with url aliases but ultimately the direct paths remain the same.

Any thoughts on how we could get around this?


texts:
I am having a watch video button which shows a YouTube video in color box. I want to show a form (webform/custom form) to appear after the video ends in the same color box itself. If users fill the form and submit it, the form should disappear, showing only the video that was ended in the colorbox. I am trying to achieve it using  using the Youtube player API but not able to achieve my objective.

Is there some other way to achieve it?


texts: Programmatically Set Default Text Editor

texts:
I have a customized module that requires tinyMCE as a library.

After module installation, I still have to set my text editor in the image above. It was found in the admin/config/content/wysiwyg.

How will I programatically set tinyMCE as a default text editor right after module installation?


texts: Class 'Drupal\user\Entity\User' not found when running drush

texts:
I am trying to run a drush on functional Drupal 7 site, however, the attempt of run drush ends with an error saying: Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php, line 571.

Any idea what may be happening?

Full output:

vagrant@1843vm:/var/www/drupalvm/drupal/web$ drush
PHP Fatal error:  Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php on line 571
[error]  Drush command terminated abnormally due to an unrecoverable error.
Error: Class 'Drupal\user\Entity\User' not found in /usr/local/share/drush/lib/Drush/Boot/DrupalBoot.php, line 571
[error]  Drush was not able to start (bootstrap) Drupal.
Hint: This error can only occur once the database connection has already been successfully initiated, therefore this error generally points to a site configuration issue, and not a problem connecting to the database.

Drush was attempting to connect to:
 drupal-version         :  7.50
 drupal-settings-file   :  sites/default/settings.php
 uri                    :  http://default
 db-driver              :  mysql
 db-hostname            :  localhost
 db-username            :  root
 db-password            :  123
 db-name                :  il
 db-port                :
 install-profile        :  standard
 db-status              :  Connected
 theme                  :  intelligent_life
 admin-theme            :  seven
 php-bin                :  /usr/bin/php
 php-os                 :  Linux
 php-conf               :  /etc/php/5.6/cli/php.ini
 drush-script           :  /usr/local/share/drush/drush.php
 drush-version          :  9.0-dev-g1c91f8b
 drush-temp             :  /tmp
 drush-conf             :
 drush-alias-files      :  /home/vagrant/.drush/drupalvm.aliases.drushrc.php
 root                   :  /var/www/drupalvm/drupal/web
 site                   :  sites/default
 modules                :  sites/all/modules
 themes                 :  sites/all/themes
 files                  :  sites/default/files
 temp                   :  /tmp
 %paths                 :  /var/www/drupalvm/drupal/web
                       sites/default
                       sites/all/modules
                       sites/all/themes
                       sites/default/files
                       /tmp`


texts: How can I disable the form confirmation message?

texts:
I'm referring to the green box that informs the user that they have successfully submitted their form.
In particular, I'm wondering if I can remove it without writing any php. Is there anything in the admin interface?


texts: Mark location on Gmap without Click on gmap

texts:
I am using Location + Gmap module. When creating a content user have to mark location on gmap. I want to to mark location on gmap automatically when user enter the values in location.

I enabled Geocoding for India and tried after set Google Maps Geocoding Accuracy to Premise, Country Level etc. but it is not marking on Gmap

I tried this documentation, But map is only displaying if I manually mark on gmap. I am using a Location CCK Field.


texts: Can I use Emoji as icon in navigation bar?

texts:
Emoji icons are 4byte UTF8 characters, the characters are not accepted in PDO, it would show errors like this question: How can I remove emoji from all user input?

Instead, I used menu_icons plugin to prepend icons as picture before the navigation text, it uses picture background in CSS, but by using this method the text and picture will be overlapped.

If emoji is not an option, is there another way to prepend an icon before navigation text?

If emoji is an option, please help me bypass the PDO exception.

Thanks.


texts: Permissions based on multiple OG groups?

texts:
Is it possible to have permissions, based on multiple organic groups?

I have 2 group content types: One 'Organisation' group type and one 'Department' group type.
There are multiple organisations and each organisation and multiple departments. Each organisation has the same departments. So for example:

ORGANISATION GROUPS:

Google
Yahoo
Microsoft
Samsung

DEPARTMENT GROUPS:

Customer Service
Management
Finance
Sales

Each user will be a member of one organisation and one or more departments.

What I want is:
If an admin adds content (like a news article), he can choose the organisations and/or departments. Users in both the chosen organisations and departments can see the content. If a user is in a chosen organisation, but not in a chosen department, he can not see the content.

If no organisation is checked, the users in all organisations can see the content (if they are in the chosen departments). If no department is checked, the users in all departments can see the content (if they are in the chosen organisations). If no organisation and no department is checked, all users can see the content.

I tried to use sub-groups, but then the admin has to choose all the (for example) 'Sales' departments of all the organisations instead of just clicking one 'Sales' department.


texts: How to customize registration process in Drupal 7?

texts:
I want to customize default registration process in Drupal 7. The registration process includes 3 steps:

Show some account types (in a page or form?). For example "personal", "business", "organization"... And users will choose their own account type.
Fill information into registration form. Each account type which users choose in step 1 has some corresponding fields.
Finish registration with an confirmation email or something else.

The registration process is similar to https://secure.payza.com/signup

Thank you for helping.


texts:
How to display block in node above comments. What i have tried is:
create region - regions[above_comments] = Above comments after in template.php i have added this to THEME_preprocess_node

$variables['above_comments'] = theme('blocks', 'above_comments');

and in my node.tpl.php i have added this below print render($content);

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

Added my content to this region, but its still empty, dpm($variables['above_comments']) - - is empty.
What is wrong?


texts:
I am building a page with a filtered table of data. I would like the filter to submit the date field information in the URL, while the op, form_build_id and the other Drupal internal fields are kept as post.

Currently if I set the method to GET all the form fields are put on the URL, naturally.

Mostly, I want to do this to keep things neat for the user.

I have read these two, related questions but:

They don't have the benefits/constraints of using the Drupal Form API.
They use static/preset GET values.

Is there any way that mixing POST and GET in Drupal 6 can be achieved?


texts:
Im using the zen theme to create a subtheme. I cannot display the breadcrumb properly. My url is using taxonomy as its parents so something along the lines of http://example.com/link1/title-article. I want the breadcrumb to be "Home > Link1 > title article.

Unfortunately I only have Home / title-article as the breadcrumb.
How can I resolve this? I havent changed the zen_breadcrumb function in the zen template..


texts: Can I create nodes through drush for particular content type

texts:
I have different content type in my site. For testing purpose, I want to add content to all content type form, but manually its not possible in such short term.

So, is any Drush command available to create node?


texts:
First off, I'm a drush newbie, just installed it and now I want to install drupal on my server, so I did a
 drush dl drupal --drupal-project-rename=Quaaoutand next I want to do a
drush si standard --db-url='mysql://quaaout:PASS@localhost' --site-name=Quaaout
but I keep getting
ERROR 1044 (42000) at line 1: Access denied for user 'quaaout'@'localhost' to database 'information_schema'
even tho I can login on the shell with mysql -u quaaout -p just fine when entering my password and also a show databases shows me the existing information_schema db. Why does it not let me proceed?
I'm on GoDaddy shared hosting with this.


texts: Preprocessed block not udpating after edit

texts:
I am preprocessing a block which seems to get cache and not showing the updated content on front end after getting edit.

My preprocess code looks like:-

/**
 * Implements hook_preprocess_block().
 */
function mymodule_aboutus_preprocess_block(&$variables) {
  $act_on_blocks = array(
    'myblockid',
  );
  if (!in_array($variables['elements']['#id'], $act_on_blocks)) {
    return;
  }
  $block = $variables['elements']['content']['#block_content'];
  $body = $variables['content']['body'];
  switch ($variables['elements']['#id']) {
    case 'myblockid':
      $variables['myblock_data']['field_title'] = t('Credits');
      $variables['myblock_data']['field_description'] = $body;
      break;
  }
}

- On Twig template
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {% include "@mytheme/myblock-partial" with {
      "title": myblock_data['field_title'],
      "content": myblock_data['field_description'],
    } only %}
  {% endblock %}
</div>


texts: Use title instead of nid for node reference contextual filter

texts:
I have a view with a node reference field as contextual filter. Instead of using
pagename/[nid] I would like to use /pagename/[title] or the pathauto url.

For uid fields there is an option to either use the uid or the name (or even both). I don't see such an option for nodes.

Is it possible?


texts: Independent search box for views taxonomy page

texts:
I'm using the "taxonomy term" view.

I would like to have a search form box independent of this page, which I will place for example in my navbar, allowing me to search among the terms of taxonomy, with autocompletion, and thus leading to the page of the corresponding term.

For example:

I have as taxonomy terms: tag1, tag2, tag3.

I'm on my home page, I type in the search form "tag2", I arrive on the page "tag2" with all the nodes having the tag "tag2", sort according to the criteria of the view.

I tried to create a separate block with views, but I do not get results.

I also tried to add a block to the "taxonomy term" view, but that does not work either.

Do you know how to do it ?


texts: What is the purpose of the "Views: views_view" component?

texts:
Using the Features module, I notice there is a "Views: views_view" component, when creating a feature, but I don't see any setting for that component.

I thought it would be list the views enabled in the site, but that doesn't happen, even if I have two views enabled.

What is the purpose of that component? Why isn't showing any settings?

I have tried with both the latest release candidate, and the lastest development snapshot, but the result doesn't change.


texts: Libraries Not Loaded After Cache Clear / Reload

texts:
I'm experiencing a problem with drupal 8

whenever I clear the cache, my custom theme's libraries(ex: the css and js) will not be loaded

and I must reinstall the whole drupal to make it works again

is there anything I can do to trace the source of the problem ?
Nothing strange is being logged in nginx and php's error log


texts: Get the user ID for a newly created user account

texts:
I'm trying to import user data from a JSON file. So far I've managed to import user entities with some fields. The next step would be to retrieve the user ID.
The code I wrote is the following one.
$users_json = file_get_contents("../import/users.json");
$users_array = json_decode($users_json, true);

foreach ($users_array as $user) {
  if(!empty($user["roles"])) {
    $values = array(
      'name' => $user["name"],
      'pass' => '',
      'status' => $user["status"],
      'mail' => $user["e_mail"],
      'field_first_name' => $user["first_name"],
      'field_last_name' => $user["last_name"],
      'field_nationality' => $user["nationality"],
      'field_introduction' => $user["introduction"],
      'field_about_me' => $user["about_me"],
      'field_current_job' => $user["current_job"],
      'field_website' => $user["website"],
    );

    $storage = \Drupal::entityTypeManager()->getStorage('user');
    $userEntity = $storage->create($values);
    if ($userEntity->save() == 1) {
      echo "User " . $userEntity->id . " saved!\n\n";
    }
    else {
      echo "User " . $userEntity->id . " updated!\n\n";
    }
  }
}

However, when I try to print the user ID, I get no data.
I've just started to use Drupal API, so I'm not very familiar with it. Is there something I'm doing wrong?


texts:
What is the file name I have to add the following script in it?

  This is actually easy to do. In the prepare() function of the node
  migration class, just set the nid and is_new to true:

public function prepare($node, $row) {
  // Preserve old nid so that old links to nodes using /node/nid still work
  $node->is_new = TRUE;
  $node->nid = $row->nid;
}

  Source link:
  How can I preserve nids during a migration?


texts: How to use a block as a field in Drupal 7

texts:
I'm working with this module which is providing me a block for uploading the file as mentioned in the doc https://drupal.org/project/jquery_file_upload

Is there a way, where I can use this block as a field while adding the content, for instance at node/add/[my_custom_content]


texts: How to reduce BARCODE FONT in barcode module?

texts: I am using Barcode module to generate barcode i have downloaded that module from drupal.org modules,i am able to reduce the rectangle lines of barcode but under the rectangles lines i have serial number like "123456" i cant able to reduce the size of it,I need to reduce the size of serial number.any suggestions.Thanks in advance


texts: How do I enable Backlinks View and What Links Here?

texts:
We used the backlinks view in D6, as well as the What Links Here tab for each node.

We're now using Commerce Kickstart 2. I don't see that View and it appears that the search_node_links table is empty.

Is this disabled because Commerce Kickstart uses the SOLR search in place of the default Search? If so, is there a way to have both the SOLR search -and- the backlinks as well?


texts: How to print barcode labels on standard printer drupal?

texts:
I am using barcode creation module to create barcode labels on standard printer.while giving print option it is not showing any barcode labels on print preview.

How can i able to see my labels?

  The directory /var/www/html/transgenic/sites/default/files/barcodes is not writable or not exist or something else wrong. You can not print barcodes without correct settings.
  An error occured while generating the barcode.
  The directory /var/www/html/transgenic/sites/default/files/barcodes is not writable or not exist or something else wrong. You can not print barcodes without correct settings.

It is showing this error..


texts: WYSIWYG and TinyMCE stripping out float: left

texts:
I've got the WYSIWYG module installed and the TinyMCE javascript library as well. I've created a text format "Rich Text" which is similar to Filtered HTML but I've added more allowed tags.

I insert an image into my text and I set it to align left which adds float: left to the markup. However, when I save and view the page, the float: left has been stripped out.

I can't find any options in the WYSIWYG configuration or my "Rich Text" format that allows me to control this. Am I missing it somewhere?

Why is my float: left getting stripped out?


texts: How to remove a specific item from the search index?

texts:
I have a content type in a D6 site that allows the creator of a node to mark the node as "withdrawn" -- he can still see it, but attempts by others to see it are caught and redirected somewhere else, like their user page.  When this node gets withdrawn, I'd like to remove it from the local search index (standard Drupal search) as well.

My somewhat brutish way of doing this is:

    db_query("delete from {search_dataset} where sid = %d", $node->nid);
    db_query("delete from {search_index} where sid = %d", $node->nid);

which seems to work -- the node stops showing up in search results.  But I'm worried about {search_total} -- there are entries there that correspond to the words in the node's content.  I can't just remove all the node's terms from {search_total}, of course; is this worth worrying about?  Or am I seriously screwing up the search index by doing this in the first place?  Thanks!


texts: How to access to the user info on the search page?

texts:
When I was trying to resolve this question: How to display the user picture on the search page? I found that in the THEME_preprocess_search_result function I can't access to the user information (I use the user search functionality) the only information about the searched users that I can use is the follow:

function THEME_preprocess_search_result(&$variables) {
    dpm($variables);
}

I can use the username and the email, I can extract from $variables['result']['title'] the username, but I think that the best way is access directly to the uid of the searched user. The problem is that I don't know how access to this information.

So, there is another way to obtain the uid of a searched user?

EDIT: I need the info of the system users (drupal users). User is not a content type.


texts: Use custom module template for content type page?

texts: I'm finding lots of examples for theming the node template of a content type, but I can't figure out how to use a template from my module as the page template for a custom node type.


texts: Is there a way to park a domain name to a single Drupal node?

texts:
Is it possible to set up a Drupal website so that other domain names can go to specific nodes but show the domain name instead of the natural URL in the address bar? Can I use the Domain module, or some other method, so that example2.com goes to example.com/page2 but still shows example2.com in the address bar?

Any internal links still go to example.com/whatever, and that's fine. The page is designed as a one page unbranded website.

I already have the domain (example2.com) pointed to our servers (example.com) and have some familiarity with setting up vhosts in apache if needed as part of the Domain module set up. I'm not sure if I'm understanding what this module does and if it will do this job. I've also posted on Server Fault but am not getting anywhere because I think I'm not asking the question properly.

Drupal 7.59. Debian and Apache


texts: Drupal uses the <h1> tag in the title of the view. I want to change title's tag <h1> to <h2>.


texts:
I'm developing a site that allows users to earn points based on site actions.  I have the site working for users and their points earned are going into a "pending" category.  The next step is that the points need to be administratively approved.

I was trying to find a way to have this action work through a page content or onclick button without having to go through config -> points -> moderation.

If anyone has any ideas or thoughts that have worked for them I'd love the help, I've been stuck on this for a few days now.

Thank you!


texts: Can you allow user to add another item without editing the administrator post?

texts: I have a field which allows multiple inputs. What I want to achieve is to allow user to add another item only and not edit the content of the post of the admin. Thank you.


texts: The best way to update existing Paragraphs in Production with newField = TRUE

texts:
how are you?
Do you know what's the best way to fill a new field inside of Paragraphs in a Production Environment?
E.g.:

I have a Paragraph called "MyParagraph" and this Paragraph has two fields "Title" and "Description";
This Paragraph is already present on our Production Environment and there are 500 nodes with this Paragraph filled;
I created right now a new field called "Show Description". This field is a checkbox and default is "Checked";

Now I need to update all of these 50 Paragraphs in production with this new field "Show Description" = TRUE
Do you know what's the best option to do that?
I used a simple hook_update to do this, and another script with a batch process.
But I want to see if there is the best solution to do this update.


texts:
I just started experimenting with the mongodb module and its fields storage module on a clean drupal install and it all seems to work fine.
But what I noticed is that the content of the 2 custom content types is stored in the same collections (fields_current.node and fields_revision.node).

Wouldn't it make sense to have a separate collection for each content type? As queries are often per content type, it should reduce the scope of your query?
Is there a possibility to do that with the current version of the module, or am I just not getting it?


texts: How to be able to use a content once in a content field?

texts:
I created a field in to a content. Let's call the content type National Anthem and the field Country. Country is a content type too.

What I'd like to do is to forbid the use of a country which has been chosen already.
*
For example, let's say that we have the country Germany, France and United-Kingdom. If I create a new National Anthem and for the field Country, I choose United-Kingdom. I now create a new National Anthem and I can only choose between France and Germany.

Thank you.


texts:
I don't know how to implement AJAX callback in hook_form_alter().

The field is plain text by default and it is populated by NID (number) of the client company. The module name is "my_car". I didn't use node reference in this field.

Here is the code:

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

    if ($form_id == 'car_node_form') {

        $clientCompanies = companyTitle(12); // TID 12

        // Replace Client company NID with title
        $form['field_car_company']['und'][0]['value'] = array(
            '#title' => 'Client company',
            '#type' => 'select',
            '#default_value' => $form_state['node']->field_car_company['und'][0]['value'],
            '#options' => $clientCompanies,
            '#required' => TRUE,
            '#empty_option' => t('- Select -')
        );
    }
}

Here I use companyTitle() function to return all companies (nodes) that have TID 12 and replace field type ("textfield" with "select") and it's content - a number with text (NID with title).

function companyTitle($tid) {

    $results = db_query("
        SELECT n.nid, n.title
        FROM {node} AS n
        LEFT JOIN {field_data_field_company_type} AS ct ON ct.entity_id = n.nid
        WHERE n.type = 'company' AND ct.field_company_type_tid = :tid
        ORDER BY n.title ASC",
        array(':tid' => $tid))->fetchAllKeyed();

    return $results;
}

I have written the function that returns NID and title of client company based on TID and title:

function ajaxCompanyTitle($tid, $companyName) {

    $query = db_select('node', 'company')
        ->fields('company', array('nid', 'title'))
        ->condition('company.type', 'company', '=')
        ->condition('type.field_company_type_tid', $tid, '=')
        ->condition('company.title', '%'.db_like($companyName).'%', 'LIKE')
        ->orderBy('company.title', 'ASC')
        ->range(0, 10);

    $query->leftJoin('field_data_field_company_type', 'type', 'type.entity_id = company.nid');

    $results = $query->execute()->fetchAll();

    return $results;
}

Now is the question of how to implement AJAX with the last function. I need text field (it does not to be a select list) with AJAX search where NID will be rendered as title (NID remaining only in the database in the field_car_company_value column).

Apparently, I don't know how to implement a callback function.

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

    if ($form_id == 'car_node_form') {

        // Replace Client company NID with title
        $form['field_car_company']['und'][0]['value'] = array(
            '#title' => 'Client company',
            '#type' => 'textfield',
            '#required' => TRUE,
            '#ajax' => array(
                'callback' => 'ajax_callback',
                'wrapper' => 'edit-field-car-company-und-0-value',
            )
        );
    }
}

function ajax_callback($string = '') {

    $matches = array();

    if ($string) {

        $clientCompanies = ajaxCompanyTitle(12, $string);

        foreach ($clientCompanies as $clientCompany) {
            $matches[$clientCompany->title] = $clientCompany->title;
        }
    }

    drupal_json_output($matches);
}


texts: How to drush rsync and sql-sync on windows with Acquia-Dev?

texts:
Answer (just to share some hours of experience):

To get rsync and sql-sync to work on remote server using Windows (w/Aquia) it is necessary to make changes to 2 files filesystem.inc and SqlBase.php

First delete cygdrive/ from  $path = preg_replace('/cygdrive/(\w):/', '/${1}', str_replace('\\', '/', $path)); in line 61 of filesystem.inc

and change drush_shell_exec('gzip -d %s', $input_file)

instead of

drush_shell_exec('gunzip %s', $input_file) in line 144 of SqlBase.php

Happy Syncing!


texts: How to get autocomplete text widgets running on an iPad?

texts:
I have a form with a couple of standard Drupal autocomplete text widgets, which work fine in desktop browsers.  However, they don't work in iPad/Safari -- the text field works properly, but I don't get any autocomplete activity.  What I can tell from a bit of log and jQuery hacking is that:

The text field is catching both .click and .touchstart() events (and probably some other touch-related events as well), and
The ajax call responsible for contacting the server to get the autocomplete results never gets made, presumably because it's not getting triggered.
Elsewhere on the site, my jQuery installation is working fine, on both desktop and iPad -- there's lots of jquery-related Bootstrap stuff going on.
I am also not getting autocomplete in Chrome/iPad, so it's not just a Safari thing.
I confess to not knowing much about jQuery Mobile, and am not doing anything with it in the site.
Via jQuery Update, I'm running jQuery 1.9 with Drupal 7.39, fully patched.  I've tried bumping jQuery up to 1.10 (as far as this version of jQuery Update will take me), but it still doesn't work.

I'm going to start diving down into the Drupal autocomplete source, but, while I'm doing that, does anybody have autocomplete widgets working on an iPad?

Update: I'm finding a lot of evidence (including my own experiments) that the keyup event is not handled by iPad (iOS really, I guess).  This is a problem for autocomplete, since some experimentation with autocomplete.js shows that it's the keyup handler that kicks off the search, via populatePopup().  I'm trying to rework the code to work with the keypress event, but it's early, and not going well thus far...

(FWIW, Android seems to handle keyup; at least, autocomplete is working on my old Galaxy Tab 2.)

Update #2: I got something working; yes, it's something of a hack.  There's a thread about what I did over at https://www.drupal.org/node/2594247, where I guess there's some chance that it might get into core.  We'll see...


texts: Multiselect values not getting saved in hook_settings()?

texts:
This is the code I have implemented in my module which is working fine!

/*
 * This is a helper()
 */
function MYMODULE_feeds($page_id = '') {
  foreach($pagefeed['data'] as $feedval) {
    $post_type[] = $feedval['type'];
    if ($feedval['type'] == 'photo') {
      if(array_key_exists('message',$feedval)) {
          $messageFeed[] =  $feedval['message'];
          if ($timeshow == 1) {
            $created_statmp = $feedval['created_time'];
          }
          $i++;
      }
      if($i == variable_get('no_feeds')) {
          break;
      }
    }
  }
  $post_type_unique = array_unique($post_type);
  $post_type_unique_serial = array_values($post_type_unique);
  variable_set('post_type_unique_serial', $post_type_unique_serial);
  return theme('MYMODULE_feed_theme', array('pagefeeds' => $messageFeed, 'time_stamp' => $created_statmp));
}

After that I have done this in my module's admin.inc file

/*
 * Implements hook_settings()
 */
function MYMODULE_settings($form, &$form_state) {
  $form['MYMODULE']['post_type'] = array(
    '#type' => 'select',
    '#title' => 'Select your post type(s) to show',
    '#default_value' => variable_get('post_type_unique_serial'),
    '#options' => variable_get('post_type_unique_serial'),
    '#multiple' => TRUE,
  );
  return system_settings_form($form);
}

Problem is that, I'm getting the values there, but when I'm saving that every field is saving the updated values, expect this field.

I'm not getting where I've made the mistake?


texts:
I'm working in a module that allows users to add notes to images. I'm using the Form API reference to create the form field. In edit-mode the HTML works (links get rendered correctly, etc.), but when saved this code is converted to standard text.

This is what I used to create the form:

  **
 * After build function to process the imagemaps widget on forms.
 */
function imagemarker_process_form_element($element, $form_state) {

  // Leave alone if we are on the field ui settings.
  if (!isset($element['#field_name'])) {
    return $element;
  }

  // Leave element when user doesn't have access.
  if (!user_access('add markers to images')) {
    return $element;
  }

  $image_style = _imagemarker_get_fields_enabled_style($element['#entity_type'], $element['#field_name'], $element['#bundle']);

  // Leave element when no image style is found for current field.
  if (empty($image_style)) {
    return $element;
  }

  $element['imagemarker'] = array(
    '#type' => 'markup',
    '#weight' => 10,
    '#suffix' => '',
  );

  if ($element['fid']['#value']) {
    $element['imagemarker']['#prefix'] = '';
    $element['imagemarker']['#markup'] = imagemarker_widget($element);
    $form['#submit'][] = 'imagemarker_widget_submit';
  }
  else {
    $element['imagemarker']['#prefix'] = '';
    $element['imagemarker']['#markup'] = t('Once an image is uploaded you will be able to add up to 3 markers to it.');
  }

  return $element;
}

/**
 * Create a widget to create and manage imagemarker.
 *
 * @param $element
 *   Form element of the image.
 */
function imagemarker_widget(&$element) {

  $settings = field_read_instance($element['#entity_type'], $element['#field_name'], $element['#bundle']);
  $image_style = $settings['settings']['imagemarker_style'];
  $langcode = $element['#language'];
  $output = '';

  if (isset($element['#default_value'], $element['#default_value']['uri'])) {
    $coordinates = _imagemarker_get_coordinates($element['#default_value']['fid']);
    $output .= _imagemarker_render($element['#default_value']['uri'], $coordinates, $image_style);
    $properties = _imagemarker_load_imagestyle($image_style);
    $output .= '';

    // Attach the javascript and css files for the imagemap UI.
    $element['#attached'] = array(
      'js' => array(
        drupal_get_path('module', 'imagemarker') . '/imagemarker.js',
        drupal_get_path('module', 'imagemarker') . '/imagemarker.admin.js'
      ),
      'css' => array(
        drupal_get_path('module', 'imagemarker') . '/imagemarker.css'
      )
    );
  }

  return $output;

}

What am I missing? Does this have to do with the Text format permissions or is this something I can fixed in the code?


texts: Is it possible to get last modified date for certain field?

texts:
Is it perhaps possible to get date and time of last modification of certain field?

Just like in table "Node" you have "created" and "modified" dates, but what about fields of certain content type?

I would like to know when certain field was last modified.

thanks!


texts: After editing .htacess for redirect some users started get the validation error on node creation page. What do I need to do?

texts:
I put the following code in my .htaccess to redirect the URL with www to the one without.

  # To redirect all users to access the site WITH the 'www.' prefix,
    # (http://www.example.com/... will be redirected to http://example.com/...)
    # adapt and uncomment the following:
    RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

The redirect works correctly. However now some users start reporting me that they get the following error on node creation when they try to save the node.

Validation error, please try again. If this error persists, please contact the site administrator.

After reading the answer to this quetion I'm guessing it's a session issue. (Please correct me if I'm wrong).

My question is do I need to add something else in .htaccess along with the code above?


texts: Add profile name field into the user page

texts:
I have overwritten the user-profile-form with hook_form_alter.

Right now there are additional fields in the user-profile-form, so the user can add more information about him/her and these fields will be visible in /user/% page.

I'm wondering is it possible to add more details in /user/% without using the user-profile-form?

Let's say to display a field "Profile of [name_of_the_user]", so anyone who enters the user profile (Example John) in the top of the page will be displayed "Profile of John".

Is there any hook for that?


texts: Create a route that redirects users to a path via parameter

texts:
I'm working on a custom module that needs to act as a mediator between a third party service and this Drupal site to manipulate some parameters. I've created a route:

my_module.process_redirect:
  path: '/my_module/{action}/process/{path}'
  defaults:
    _controller: '\Drupal\my_module\Controller\RedirectController::process'
  requirements:
    _access: 'TRUE'

Ideally, I'd like the destination route to be modified based on the value of {action}.

Is there any way to pass a path with slashes as a parameter? For intance:
/my_module/abc/process/path/to/page'
would result in $action = 'abc' and $path = 'path/to/page

Beyond replacing the slashes with another character and processing them in my controller I can't seem to find a way to make this work. This route will be user-facing so I'd like to keep it looking fairly clean if possible.

Thank you!


texts: How to get the Object based on File ID (FID)

texts:
I'm inside mytheme_image_formatter($variables) function and I got the image's FID (from $fid = $variables['item']['fid']).

Question:
Is there a way to know which object is using the image file?

Using file_usage_list(file_load($fid)), I can see which objects may use the file. But I want to know which one is using the image file, inside my function.

Tried to use mytheme_preprocess_image(&$variables), but I also found the same situation.

This is the same problem as discussed here, without a solution.

Thanks


texts: Help outputting Drupal View JSON data using getJSON function

texts:
I'm trying to return the view data and display it in a list for verification.

It is sending for the data and seems to receive it (I get a 200), but it is not outputting the data.

Any help much appreciated!


texts:
I get the error shown below while trying to implement dependent dropdown for country state as shown below
while trying to submit form which implements  AJAX in drupal 8 for country - state dropdown I get the error
Error "An illegal choice has been detected. Please contact the site administrator.". How can I make sure default value of State is retained like its retained for Country ?

namespace Drupal\custom_changes\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\custom_changes\NameTable\NameTable;
use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;

/**
 * Simple Form
 *
 */
class CustomDicForm extends FormBase {
  /**
   * @inheritdoc
   */
  public function buildForm(array $form, FormStateInterface $form_state )
  {

    $form['country'] = [
      '#type' => 'select',
      '#title' => $this->t('Country'),
      '#options' => [
        '' => t('Select'),
        'IN' => t('India'),
        'GB' => t('UK (Great Britain)'),
      ],
      '#ajax' => [
        'callback' => '::stateCallback',
        'event' => 'change',
        'wrapper' => 'state-list',
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Updating States...'),
        ],
      ],
    ];
    if (isset($form['#options'])) {
      $form['state'] = [
        '#type' => 'select',
        '#prefix' => '
',
        '#suffix' => '
',
        '#title' => $this->t('State'),
      ];
    }
    else {
      $form['state'] = [
        '#type' => 'select',
        '#prefix' => '
',
        '#suffix' => '
',
        '#title' => $this->t('State'),
        '#options' => ['' => t('Select')],
      ];
    }
    $form['submit'] = [
      '#type'=> 'submit',
      '#value' => t('Submit'),
    ];

    return $form;
  }
  public function stateCallback(array &$form, FormStateInterface $form_state) {
     $country = $form_state->getValue('country');
     $form_state->setValue('state', '');
     $form['state']['#options'] = ['' => t('Select')] + $this->getAllStates(
       $country
     );

     return $form['state'];
  }

  /**
   *
   *  Get the State from Country
   *  @return array $states
   *
   */

  public function getAllStates($country) {
    if ($country == "GB") {
      // as GB does not give values so adding hard coded values
      return ['A','B','C','D','E','F'];
    }
    else {
      $subdivisionRepository = new SubdivisionRepository();
      // Get the subdivisions for Brazil.
      $states = $subdivisionRepository->getAll([$country]);
      $in_states = array();
      foreach ($states as $key => $state) {
        $in_states[] = $key;
      }
    }
    return $in_states;
  }

  /**
   * @inheritdoc
   */
  public function getFormId()
  {
    return 'custom_changes_dic_name_form';
  }

  /**
   * @inheritdoc
   */
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    parent::submitForm($form, $form_state);
    $form['country']['#default_value'] = $form_state->getValue('country');
    $form['state']['#options'] = ['' => 'Select'] + $this->getAllStates($form['country']['#default_value']);
    $form['state']['#default_value'] = $form_state->getValue('state');
    $first_name = $form_state->getValue('first_name');
    $last_name = $form_state->getValue('last_name');
    //@todo check how to pass exception
    $this->nameTable->insertData($first_name, $last_name);
  }

}


texts: Programmatically create user reference field

texts:
I want to add a user reference field in taxonomy term. I create field and it's instance:

$field = ['field_name' => 'mymodule_employee',
        'label' => t('Employee'),
        'type' => 'entityreference',
        'cardinality' => 1,
        'settings' => [
            'target_type' => 'user',
            'handler' => 'base',
            'handler_settings' => [
                'target_bundles' => ['user']
            ],
        ],
];
field_create_field($field);

$instance = ['mymodule_employee' => [
            'entity_type' => 'taxonomy_term',
            'bundle' => 'my_vocabulary',
            'field_name' => 'mymodule_employee',
            'label' => t('Employee'),
            'widget' => array(
                'type' => 'options_select',
                'active' => 1,
            ),
            'settings' => array(
                'target_type' => 'user',
                'handler_settings' => array('target_bundles' => null),
                'handler' => 'base',
            ),
            'display' => array(
                'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
            ),
            'required' => 0,
            'default_value' => null,
        ],
];
field_create_instance($instance);

Everything goes ok. But when I'm creating the term and try to choose a user there is an empty list. When I go to the field settings in admin form and just save it, everything begins to work.

What do I forget creating field and instance?


texts: (Answered) Ajax link for anonymous users to delete node they created if $_SESSION exists. Is node's created timestamp secure enough in link?

texts:
I'm allowing anonymous users the ability to create nodes using a form. But I want to allow them the ability to delete them again straight away.

Instead of forcing them to create an account and take control of the node, I want to just give a use-ajax link that deletes the node. The $_SESSION variable would have the NID and the code to print the link would check for that.

To add some semblence of security, I'm thinking of adding the timestamp in the link and my module only deletes the node if the timestamp matches.

Is that secure enough? The same content type will be used by logged in users so it has to be fool-proof.


texts: add custom data attributes to block from block configuration page

texts:
Here is what I would like to accomplish:
 1. Add data attributes to block (for example: data-key="value")
 2. Nice to have: add a text area to block config page where i can enter data attribute key-value pairs (one per line) and have them added to the block.

Any guidance is greatly appreciated


texts: How to define "field change" event in hook_notifications()

texts:
I want to define my own events using hook_notifications(). I started with the tutorial here. I've been analyzing the code and so far I've been trying to find out where exactly I am supposed to describe the "field changes value" action.

My presumption is that that under "subscription fields" I should add the two relevant fields.

Later on in the tutorial, in the "event types" part, this code is provided:

$types[] = array(
    'type' => 'node',
    'action' => 'update',
    'name' => t('[type-name]: [title]'),
    'line' => t('The [type-name] has been updated'),
    'digest' => array('node', 'nid'),
    'description' => t('Node update'),
  );
  $types[] = array(
    'type' => 'node',
    'action' => 'comment',
    'name' => t('[type-name]: [title]'),
    'line' => t('New comment by [comment-author-name]: [comment-title]'),
    'digest' => array('node', 'nid'),
    'description' => t('Node comment'),
  );
  return $types;

These are just examples of a node being updated and a comment being added, but, apart from guessing, I don't know how a "custom field being updated" event should be defined and I would be happy to get some help on that.


texts: AJAX loading of a view on click of a button?

texts:
I want to switch between two methods of sorting and displaying items in Views by toggling a button. My exposed filters are in the URL so I want to include the query in the path in order to keep the exposed filter results. Both displays of the view have "use ajax" set to "yes".

My link is :

$link_path = ($display_data->display_options['path'] . '/nojs');
$query = drupal_get_query_parameters();
$toggle_link = l($toggle_icon, $link_path, array('html' => true, 'query' => $query, 'attributes' => array('class' => array('use-ajax'))));

Which outputs something like:

[omitted SVG path for brevity]

In a js file in my theme, I have:

    /**
     * Toggle button and ajax views
     */
    var viewId = settings.mytheme_toggle_view.view;
    var viewDisplayId = settings.mytheme_toggle_view.current_display;
    var viewOtherDisplayId = settings.mytheme_toggle_view.other_display;
    $.ajax({
        url: settings.basePath + 'views/ajax/' + settings.mytheme_toggle_view.query,
        type: 'post',
        data: {
          view_name: viewId,
          view_display_id: viewOtherDisplayId,
          view_args: {}, // your views arguments
        },
        dataType: 'json',
        success: function (response) {
            var newView = ($(response[1].data));
            $(".view-display-id-" + viewDisplayId).replaceWith($(newView));
        }
    });
    /* End views ajax stuff. */

What happens now:

I go to my view and select my exposed filters and hit "apply"
I arrive at my view's default display page
Before I can click anything, AJAX fires and replaces the view content with the alternative view content.
If I click the toggle, it is a link (with full page reload, not AJAX) to the default display page again.
Step 3 repeats.

What I want is for the view to

Not change on pageload, but wait until the toggle button is clicked
Be able to be toggled back and forth rather than only toggling once and then becoming a regular, page-reloading link.
Preserve the exposed filters
Have the pager still work (currently is a link to some JSON output of the settings object).


texts: Cannot override template provided by contrib module in theme

texts:
I'm leveraging the Superfish module for our menus but need to tweak the output a bit.
Normally I'd just copy the relevant template file (in this case superfish-menu-items.html.twig) into my theme and call it a day.
This isn't working in this case. Any ideas why that might be and how to get around it?

Before voting to close this issue, I'd ask that you request information you think would be valuable to providing additional specificity.
I can only assume that this issue is due to some issues with the construction of the Superfish module itself and its theming implementation, so I'm trying to figure out how to work around this.
Any solution would likely be applicable in similar contexts as well.

I've tried modifying the element in hook_theme() and hook_theme_registry_alter() to point to my theme's implementation of the template, but in both cases I end up hitting

  Twig_Error_Loader: Template is not defined errors.

EDIT: I'd already enabled debugging prior to posting. Please stop suggesting that I enable debugging. This is what is shown before and after copying the template into my theme. I've cleared caches and verified the template name in my theme.


texts: Menu Block (or custom menu display): expand immediate children of active item

texts:
I need to show a menu which only displays nodes one or two levels into the menu hierarchy, unless these nodes are immediate children of the node currently being viewed, in which case they should also be shown. (I explain what I'm after more fully in the lengthy 'example' below.) The Menu Block module almost lets me do this, but lacks a setting to expand the immediate children of active item. I added this as a feature request for Menu Block but have had no reply. Is there any way I can implement this myself, either using Menu Block or writing code to display the menus myself? Any code pointers would be very helpful.

(Background info: I'm using Drupal 7)

An example of what I'm after

Suppose you have a menu with these items (with the number of dashes before them representing their level):

-i1
--i2
--i3
---i4
---i5
----i6
--i7

If in Menu Block I set my menu block up with 'Starting level' = '1st level' and 'Maximum depth'=1 then it'll look like:

-i1
--i2
--i3
--i7

However, I'd like there to be an 'expand the immediate children of the active item' setting in Menu Block. If this setting were chosen then if the active item were i3 or i4 you should see:

-i1
--i2
--i3
---i4
---i5
--i7

And if it were i5 or i6 you'd see:

-i1
--i2
--i3
---i4
---i5
----i6
--i7


texts: Pathauto URL allowing unauthorised user to view

texts:
I have a content type that only authorised users are able to view i.e. mysite.net/node/66 (Access denied message for non authorised users) but when I view the same content using an alias of node/66 i.e. url mysite.net/content/for-registered-users-to-view (node/66) I'm able to view this content whether I'm logged in or not.

I would like to have the same (Access denied message for non authorised users) when viewing this alias. Can anyone tell me why this is happening I've checked my permission but I just can't work it out. I'm using Pathauto (version 7.x-1.3) to automatically create the aliases


texts:
I'd like to view my block on pages where the content type = booking and where the address is node/add/booking (basically add, edit and view nodes), how can I accomplish this? So far my code only shows on pages where content type = booking (i.e. view and edit nodes).

<?php
// Change the type to the one you want to match on
$desired_type = 'booking';
if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
  $node = node_load(arg(1));
   return $node->type == $desired_type;
}

return FALSE;
?>