error SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

1 month 3 weeks ago

I'm currently migrating my website to D8 and I'm having some issues updating my NEW nodes to match with my live D7 site.

I get a few of these for each content type. I think it's from creating "test page" and the node ID is taken.

I get a few of these warnings:

[error] SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'e0891884-4da7-45c9-a1b5-808c8f821cfa' for key 'node_field__uuid__value': UPDATE {node} SET vid=:db_update_placeholder_0, type=:db_update_placeholder_1, uuid=:db_update_placeholder_2, langcode=:db_update_placeholder_3 WHERE nid = :db_condition_placeholder_0; Array ( [:db_update_placeholder_0] => 61287 [:db_update_placeholder_1] => festival [:db_update_placeholder_2] => e0891884-4da7-45c9-a1b5-808c8f821cfa [:db_update_placeholder_3] => und [:db_condition_placeholder_0] => 3943 )

I tried drush migrate-import upgrade_d7_node_festival --update , but that didn't work. Is there a way to overwrite my test nodes when migrating? Do I have to go and delete all the table nodes in my DB then rerun the migration?

Thank!

user101672

I have 2 commerce feeds imports, one must run before the other

1 month 3 weeks ago

I have a drupal 7 commerce site, each day our client uploads a .csv with updates to approx. 4000 products, including published status.

2 imports have been configured, 1 to update the product information and the other to update the product references (node/display) - both read the same .csv.

The importers must run 3 times a day, in order to avoid errors, the product importer must execute before the reference importer. If we use Drupal cron, both will start at the same scheduled time, which leads to errors.

What we really want is to run the product importer until it is completed (multiple times if necessary), and only then to run the reference importer. All of the above 3 times a day.

I imagine there is a hook allowing execution of a specific importer, so I can run it via bash cron, but I don't know where to begin looking, any pointers would be appreciated.

RominRonin

How do I remove webforms from content types?

1 month 3 weeks ago

Currently, our site is built so that anytime a specific type of new content is created, the page automatically includes a form required for the end user. Due to tracking issues we're having with other software, we would like to remove these automatic forms from this specific resource type so that the resource is no longer gated.

Can anyone explain how I can make this change to my current content type so that we're not forced to create a whole new content type and replacing things systematically?

user26108

Warning: file_put_contents(): Filename cannot be empty

1 month 3 weeks ago

After updating Drupal 8 to Drupal 9, the following error is displayed on the website page:

Warning: file_put_contents(): Filename cannot be empty in /var/www/html/web/modules/contrib/devel/src/DevelDumperManager.php on line 108

Although it is not in the logs. But there is a similar one:

Warning: file_put_contents(): Filename cannot be empty in Drupal\search_api_solr_devel\Logging\SolariumRequestLogger->preExecuteRequest() (line 148 of /var/www/html/web/modules/contrib/search_api_solr/modules/search_api_solr_devel/src/Logging/SolariumRequestLogger.php)

Perhaps these errors are somehow related. How I do fix these errors?

I tried debugging and this is what xdebug shows for the first error:

nathan111777

How to alter node links

1 month 3 weeks ago

I have few existing node nodes which contains link <a href="/some/link/here">Click here</a>. Now I want to update all links to <a href="/updated/some/link/here">. Is there any way to do this in Drupal8 via code.

user739350

Getting a menu delivered via REST

1 month 3 weeks ago

I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.

I can successfully return this example json using this function when I hit the URL.

public function get(EntityInterface $entity) { $result = array(); for ($i = 0; $i < 10; $i++) { $temp = array( 'title' => 'Test ' . $i, 'href' => '#/' . $i ); array_push($result, $temp); } return new ResourceResponse(json_encode($result)); }

I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.

I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.

How do I get menu item titles and paths based on the menu machine name?

EDIT

Ok, sort of figured it out.

public function get($entity) { $menu_name = $entity; $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name); $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters); $renderable = \Drupal::menuTree()->build($tree); $result = array(); foreach (end($renderable) as $key => $val) { $temp = array( 'menu_item' => $val, 'route' => $key ); array_push($result, $temp); } return new ResourceResponse(json_encode($result)); }

Right now that will output:

[ { "menu_item":{ "is_expanded":false, "is_collapsed":false, "in_active_trail":false, "attributes":"", "title":"Home", "url":{ }, "below":[ ], "original_link":{ } }, "route":"standard.front_page" }, { "menu_item":{ "is_expanded":false, "is_collapsed":false, "in_active_trail":false, "attributes":"", "title":"Communities", "url":{ }, "below":[ ], "original_link":{ } }, "route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7" } ]

any idea why url or original_link are empty?

Ronnie

Twig template for just one page in a view

1 month 3 weeks ago

I have a Drupal view (Product Section) where I have a master view. This is the view I'm currently using for Computers, Cell Phone, and other pages I am still creating.

I also have a Product Shop page, which is almost like the parent page. For this page, the path is /products, for Computers is /products/computers, and so forth.

In my theme folder, inside of the templates folder, I created a page--products.html template. This works great, but this template gets used not only by the /products pages but also the products/page-name-here pages.

  1. How do I change this template to only target /products and not products/page-name-here. Would I just have to change the template name to something more specific?
  2. Inside of this template, can I do an if statement something like the code below that will only target that /product page? Let's say I end up keeping the template on all the pages, but I want to add code that only shows up if it's on /products and not products/page-name-here. Maybe I could target it by its unique ID. How can I achieve this?
{% if page = 'page-name' %} // This will only show on /products. {% endif %}
hisusu32

Can I add elements to a field widget with AJAX?

1 month 3 weeks ago

I want to add fields depending on the first option selected. I also made a form with a similar behaviour but it wasn't a field widget.

I used this module as an example to make the form

I'm not sure if the way I implement this AJAX behavior should be different in a widget.

Can the behavior of this form be implemented in a field widget? I'm trying to look for examples of specifically field widgets implementing this but I still haven't found anything that could help `

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $value = isset($items[$delta]->value) ? $items[$delta]->value : ''; $element = []; // Gather the number of names in the form already. $num_names = $form_state->get('num_names'); // We have to ensure that there is at least one name field. if ($num_names === NULL) { $name_field = $form_state->set('num_names', 1); $num_names = 1; } $element['breakpoints'] = [ '#type' => 'select', '#title' => $this->t('Breakpoint group'), '#options' => $this->getBreakpointsGroups(), '#default_value' => $value, '#empty_option' => $this->t('-Select a breakpoint group-'), ]; $element['images_fieldset'] = [ '#type' => 'fieldset', '#title' => $this->t('Load images for each breakpoint'), '#prefix' => '<div id="breakpoint-wrapper">', '#suffix' => '</div>', ]; for ($i = 0; $i < $num_names; $i++) { $element['images_fieldset']['image'][$i] = [ '#type' => 'image', '#title' => $this->t('Image'), '#name' => "Name" ]; } $element['images_fieldset']['submit'] = [ '#type' => 'submit', '#title' => 'Submit', '#submit' => ['::submitForm'], '#value' => $this->t("submit"), '#ajax' => [ 'callback' => '::loadImageFields', 'wrapper' => 'breakpoint-wrapper', ], ]; return ['value' => $element]; } /** * Returns a list of breakpoints. * * @return array * An associative array of breakpoints, suitable to use as form * options. */ protected function getBreakpointsGroups() { $breakpoints = \Drupal::service('breakpoint.manager')->getGroups(); $breakpoint_names = array_keys($breakpoints); $breakpoint_group = array(); foreach ($breakpoint_names as $name) { $breakpoint_group += [$name => $name]; } return $breakpoint_group; } protected function submitForm($form, &$form_state) { $state = $form_state->getTriggeringElement(); $breakpoint= $state['#value']; $array = array(); $breakpoint = \Drupal::service('breakpoint.manager')->getBreakpointsByGroup($breakpoint); $breakpoints_name = array_keys($breakpoint); foreach ($breakpoints_name as $breakpoint_definition) { $mediaQuery = $breakpoint[$breakpoint_definition]->getMediaQuery(); array_push($array,$mediaQuery); } $name_field = $form_state->get('num_names'); $form_state->set('num_names',count($array)); $form_state->setRebuild(); } public function loadImageFields(array $form, FormStateInterface $form_state) { return $form['images_fieldset']; }

}

Burly Uranus

How to display a form in controller method

1 month 3 weeks ago

I have a form defined in mymodule/src/Form/myForm.php

namespace Drupal\mymodule\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; class myForm extends FormBase { /** * Specify the form ID. */ public function getFormId() { return 'mymodule_myform'; } /** * Build the actual form. */ public function buildForm(array $form, FormStateInterface $form_state) { // Form API code here...

Originally, this routing worked fine and the form displayed at the correct path:

mymodule.single_tab: path: '/node/{node}/edit/performance' defaults: _form: '\Drupal\mymodule\Form\myForm' _title: 'Add performance'

Then I needed to add a custom access check, restricting to a specific content type:

mymodule.single_tab: path: '/node/{node}/edit/performance' defaults: _title: 'Add performance' _controller: '\Drupal\mymodule\Controller\mymoduleController::content' requirements: _custom_access: '\Drupal\mymodule\Controller\mymoduleController::checkAccess'

The access check works fine. Now I think I have to display my form in the controller:

namespace Drupal\mymodule\Controller; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Form\FormBuilderInterface; use Drupal\Core\Access\AccessResult; use Drupal\node\Entity\Node; /** * Controller for Add Performance single tab. */ class mymoduleController extends ControllerBase { /** * Returns the add single performance form. */ public function content() { $form = $this->formBuilder->getForm('Drupal\mymodule\Form\myForm'); return [ '#type' => 'markup', '#markup' => $form ]; }

This fails to display the form, and I get:

Call to a member function getForm() on null

I tried defining my form builder class inside the controller instead, but same result. What am I doing wrong?

pushka

Filter based on the current node field value

1 month 3 weeks ago

I have a Webform where it's used to get product comments. This webform is exposed in a node page and has a field that is populated automatically with a value from the current node, lets say "Manufacturer" and this is just a plain text field. So there are multiple products with the same manufacturer. For example Intel i5 2500k and Intel Motherboard Model-No-1.

I'm using the Webform 7.x-4.x for this. What I have done is use the Webform Submission Data field in Views to display the different data but now what I'm trying to do is when I go to a product, I want the view to filter all the Webform submission by the current product's manufacturer. So when I go visit the i5 2500k page, the view will list also the Webform submissions for the Intel motherboard.

Leolando Tan

How to hide nodes in a VIEW where the user is not referenced?

1 month 3 weeks ago

This is a follow-up to How to show nodes where the user is (not) in the reference field with Views?

I have a node with multiple user references and need a node VIEW that hides all nodes where the current user is NOT referenced. So, if the current user is not referenced, the node should not show up. The problem I just can't solve is that the node still shows up when other user are referenced (using exclude, it only excludes the current user from display, but it still displays the nodes for each other user that is referenced). I have unsuccessfully tried views_distinct module and VIEWs own "distinct" query settings.

If the user is referenced, the node should show up (this works from the above mentioned question)

CLARIFICATION:

Basically, it’s for a simple pay-per-view site. I need 1 (or 2, whatever works) VIEWS that shows the videos where the user has purchased access to (where he is referenced) and where the user has not purchased access to (where he is not referenced). After 48 hours the references are removed using rules scheduler.

Ideally in one VIEW, when the user is referenced, the link should be „watch“, where the user is not referenced, it should read „buy“ using VIEWS conditional and rules link. But two separate VIEWS are also ok.

Right now I have a content view (also tried it with a user view unsuccessfully, but this might be a saner approach?!). All of that works well with the notable exception of showing the nodes with multiple user references.

UPDATE:

Added a screenshot using the views argument substitutions.

UPDATE 2:

I tried it with regExpressions and views substitutions. The UID of the currently logged in user is passed as !1, but what is the correct regEx syntax to show only the nodes, where this user is not referenced?

This does not work as value of the operator on the useraccess field filter:

^***!1***

SOLUTION

Oh boy, this was a ride. Finally figured out a solution. Posting it if someone needs it. Basically, I added the username in the url and do a contains text comparison using views conditional. ID from the logged in user did not work as contains also shows user ID "13" or "14" when the user "1" is logged in. Simply excluding did not work in those cases where other users are referenced as well.

user24957

Can't hide fields in user registration form at new menu path

1 month 3 weeks ago

I have a menu path which rendered User Registration Form. The problem is I did hide fields like "Email", "password" and "status" by setting #access to FALSE. It is not working.

When I have done the same thing in hook_form_alter(), it does work.

This is my code.

/** * Implements hook_menu(). */ function MY_MODULE_menu() { $items['admin/author/create'] = array( 'title' => t('Author'), 'page callback' => 'MY_MODULE_author_form', 'type' => MENU_CALLBACK, 'access callback' => TRUE, ); return $items; } /** * Author form. */ function MY_MODULE_author_form() { drupal_set_title('Create Author'); // Getting User Register Form $form = drupal_get_form('user_register_form'); // Change Username to Author Name $form['account']['name']['#title'] = 'Author Name'; // Exclude User Registeration Elements $form['account']['mail']['#access'] = FALSE; $form['account']['pass']['#access'] = FALSE; $form['account']['status']['#access'] = FALSE; // The path to which the form will be submitted. $form['#action'] = url('admin/people/create'); return $form; }

I think I can alter the form in MY_MODULE_author_form().

Is there anything wrong with my code?

user8887

Views Grouping field:Add Ordered class to Grouping row

1 month 3 weeks ago

I use Views and Grouping field to integrate my data. But i need each grouping row ordered.

I want to override the views-view-grouping.tpl.php, and change the "view-grouping" class to "view-grouping-1","view-grouping-2","view-grouping-3"...

The original code is belowed:

<?php /** * @file * This template is used to print a single grouping in a view. * * It is not actually used in default Views, as this is registered as a theme * function which has better performance. For single overrides, the template is * perfectly okay. * * Variables available: * - $view: The view object * - $grouping: The grouping instruction. * - $grouping_level: Integer indicating the hierarchical level of the grouping. * - $rows: The rows contained in this grouping. * - $title: The title of this grouping. * - $content: The processed content output that will normally be used. */ ?> <div class="view-grouping"> <div class="view-grouping-header"><?php print $title; ?></div> <div class="view-grouping-content"> <?php print $content; ?> </div> </div>

The File is located at all/module/views/theme/

Does someone meet the same problem before?

Thx for help.

cobenash

Want parent MENU_LOCAL_TASK tab to show when on a child page

1 month 3 weeks ago

I have a set of local task menu items defined in my module. This includes the following items:

  • control => MENU_NORMAL_ITEM
  • control/jobs => MENU_DEFAULT_LOCAL_TASK
  • control/jobs/% => MENU_???
  • control/download => MENU_LOCAL_TASK
  • control/settings => MENU_LOCAL_TASK

The three menu items (jobs, download and settings), display as tabs, as I want. When someone clicks through to see a particular job, I want this to show as having the jobs tab selected.

If I add MENU_LOCAL_TASK to "control/jobs/%," the tabs show up, but I get notice errors (because Drupal is trying to define a link to % and can't know that). If I don't, the specific job page does not have any tabs at the top.

Have I misunderstood anything? Can I achieve this in another way?

artfulrobot

Change language of a JS element when language has been changed from Drupal language switcher?

1 month 3 weeks ago

First of all, sorry for the really confusing title, but I have no idea how to make it more reader friendly. On my website, there are three languages: English, Finnish and Swedish. The user can change between these languages from the default Drupal language switcher. Now the key part of the website comes from an API that I think is in JS. That JS element has its own language changing parameter.

src="//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=sv&leaflet_gshim=1">

So in order to change the language of the JS element I would need to change that "lang=" part to what language I want. I have that script with the address to the API in my page.html.twig file to make the API call to work all across the site.

Is there a way to change the lang=sv to lang=en and lang=fi when the user changes the language through Druapl language switcher?

From the companys API support they said:

you have different pages for different languages: website.fi/drupal/ (englisch) website.fi/drupal/sv website.fi/drupal/fi This means that you should have a different script tag for each of these paths. I guess Drupal allows that with help of a language variable that is accessible in your page template. (But I really know little about Drupal, so that's just a guess)

I am sorry for a long and confusing post, but it is really crucial to get this to work and I am losing my mind. PS! I am really new to Drupal.

Hert Niks

How do I set up a More Link in a View's Pager?

1 month 3 weeks ago

I have a View and am using the Pager to display a specific number of items, limited to 4. I want to create a "More" link to link to the rest of the items.

I've set my view up as such:

But no More link is appearing, even though I have more than 4 items and even though the helper information says:

This will add a more link to the bottom of this view, which will link to the page view. If you have more than one page view, the link will point to the display specified in 'Link display' section under advanced. You can override the url at the link display setting.

I've looked through the HTML to ensure the link is not hidden by anything else. It's simply not present.

Would anyone know how to get this working?

MeltingDog

How do I get the entity ID from a view row and pass it along to the item list template?

1 month 3 weeks ago

I have a view which returns rows of entities. Each entity has several multi-value fields.

The structure is kinda like this:

  • Field 1:

    • Item A
    • Item B
    • Item C
    • ...
    • Item H
  • Field 2:

    • Item A
    • Item B
    • Item C

Field 2 holds values that are related to Field 1 Item B. When displaying Field 1 in the view results I'd like to be able to display them like:

Field 1: Item A, Item B (Field 2 Item A, Field 2 Item B), Item C, Item D

Because its a multi value field Views is using the item_list template. My plan was that I would adds some conditionals to this template so that if Field 1 Item B was to be shown, I would use Twig Tweak to add the values from Field 2 inline to it. The only problem is that to do that I need the row's entity ID. For the life of me, I can't figure out how to pass this information into the item_list template. This template seems completely removed from the view and doesn't have a way to reference it.

I've been trying various functions in my theme file to get the result row NID and pass it along as a variable into the list_item template, but have had nothing but failure. I've figured out how to get a custom variable into the item_list template preprocess_item_list, but I can't figure out how to get the row NID into this function.

Any help would be appreciated.

fallenturtle

Error creating a status transition programmatically - Missing bundle for entity type workflow_transition

1 month 3 weeks ago

I'm currently working on a migration project from D7 to D10. I have a form that needs to go through several steps from creation to completion, here are some of them:

  • New Request
  • Under Analysis
  • Manager Approval

The status transition is done through a button called "Save and Submit" which, when clicked, the form should go directly from the "Creation" status to the "Under Analysis" status.

For this, I'm using the "Workflow" contrib module - https://www.drupal.org/project/workflow - and created a status transition programmatically. But when requesting the transition I am getting an error.

Can anyone help me with this problem, please?

Here is my code and the error received:

public static function createNodeStatusTransition($node_id, $workflow_id, $transition_id, $field_name, $to_state_id, $user_id = NULL) { $node = Node::load($node_id); if (!$node instanceof EntityInterface) { throw new \InvalidArgumentException("Node with ID $node_id does not exist."); } $workflow = Workflow::load($workflow_id); if (!$workflow) { throw new \InvalidArgumentException("Workflow with ID $workflow_id does not exist."); } $current_state = $node->get($field_name)->value; $to_state = WorkflowState::load($to_state_id); if (!$to_state) { throw new \InvalidArgumentException("Workflow state with ID $to_state_id does not exist."); } if ($to_state->getWorkflowId() !== $workflow_id) { throw new \InvalidArgumentException("The 'to' state does not belong to the workflow with ID $workflow_id."); } $transition = WorkflowTransition::create([ 'entity_type' => $node->getEntityTypeId(), 'entity_id' => $node_id, 'field_name' => $field_name, 'from_sid' => $current_state, 'to_sid' => $to_state_id, 'uid' => $user_id ?: \Drupal::currentUser()->id(), 'timestamp' => \Drupal::time()->getRequestTime(), ]); $transition->save(); \Drupal::messenger()->addMessage(t('The transition was successfully created for the node %node_title.', ['%node_title' => $node->label()]));

}

ernanesabino
Checked
10 hours 28 minutes ago
most recent 30 from drupal.stackexchange.com
Subscribe to Drupal StackExchange feed