texts: How to attach a paragraph to a node using node_updatehook?

texts:
I am trying to attach a paragraph, to a node. I am currently trying to do it in node_update hook.

The value for paragraph will come a custom field. Currently am trying to achieve this with hard-coded value. I tried two methods, but both are not working.

Method 1

function my_module_node_update(Drupal\Core\Entity\EntityInterface $entity) {

  $paragraph = Paragraph::create([
  'type' => 'attendance',
  'field_stakeholder' => array(
      "value"  =>  '. Roshni, UPS Kharwna from Dunda, Uttarkashi (UTK_130000377) (49645)',
    ),
  ]);

  $paragraph->save();

//this is working
 dpm($paragraph->id());

 $current[] = array(
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    );

   $entity->set('field_attendance', $current);
   $entity->save();

}

Method 2

function my_module_node_update(Drupal\Core\Entity\EntityInterface $entity) {

  $paragraph = Paragraph::create([
  'type' => 'attendance',
  'field_stakeholder' => array(
      "value"  =>  '. Roshni, UPS Kharwna from Dunda, Uttarkashi (UTK_130000377) (49645)',
    ),
  ]);

  $paragraph->save();

//this is working
 dpm($paragraph->id());

   $entity->field_attendance->appendItem($paragraph);
   $entity->save();

}

However, I am getting an error:

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity
  constraint violation: 1062 Duplicate entry '213436' for key 'PRIMARY':
  INSERT INTO {node_revision} (nid, vid, langcode, revision_timestamp,
  revision_uid, revision_log) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 41374
  [:db_insert_placeholder_1] => 213436 [:db_insert_placeholder_2] => en
  [:db_insert_placeholder_3] => 1535117690 [:db_insert_placeholder_4] =>
  1 [:db_insert_placeholder_5] => ) in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 777 of
  /home/rupali/fa-rupali/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

I feel like the error is coming as the hook is called twice. The code is working till paragraph creation. I am able to verify it.


texts: Assign submission to a user referenced in a webform

texts:
I'm trying to solve this problem:

A webform contains a user entity reference field

User A submits a webform that references user B

After submitting the data I want user B to be able to edit this (and only this) submission.

I haven't found a way of doing this, is this possible.


texts: I'm using drupal commerce for ecomerce project.  Shopping cart views with 100-200 line_items renders extremely slow - 5-10sec. How to fix it?


texts: Render a referenced node via token in field

texts:
This feels like it should be something people have tried, but I can't find anything after some googling. My use case is simple, I have a node type that only has 2 fields, body and media. The media field is, in fact, an entity reference field pointing to another node type (this is done because there are special cases where the media needs to be rendered HTML). All, I'm trying to do is render the referenced media field, by delta, in the main content area.

I can use the token [node:field-media:0] and print the title with no problem, I can print individual fields without an issue. Is there an existing method to print the rendered entity? I'm good with it using the default view mode.

I know I can code this up, but it seems like such a simple thing I figured there would already be a contrib module out there.


texts: Showing each node's creation date but in the content-list (instead on in each node)?

texts:
In Drupal 7, we can show nodes' creation date very easily by going to the edit back-end forum, scroll to the lower part of the form, and there add "show node creator and creation time date" (or a similar phrasing).

But, AFAICR this does not show creation date for all such nodes in the content list.

Is there a way to add a creation date column to the node list in the "content" page of the site?

I found a patch that supposed to do so but it seems to have failed testing.

I don't mind if the way to solve it is via a module or a codepiece I could implement somewhere with or without further customization.

Maybe someone here has a ready solution for this?

*As can be seen in the above image - there isn't any "sort by creation date column" here...


texts:
I am actually trying to load the printmail form inside a colorbox. But when I am trying to build up a link like this:
Send as email

The colorbox opens, but returns "This content failed to load."
Someone got an idea how to workaround that?


texts: how to render a welcome page in page--front.tpl.php

texts:
I have a template page--front.tpl.php. It contains all different stuffs and a welcome message, wrapped in a div container. Since, I want it to be editable, I created a new basic page called 'Welcome message'. It opens in a separate node 'welcome-message'.

Now I want this to be rendered in page--front.tpl.php in given div container. Any suggestions?


texts:
I'm having problems with adding a form and text-content into a block. To get both, form and text, into my block, I use render() on my form, but I read, this isn't the best way to do, but don't found another way. Anyone knows how to get both into the content without using render()?

function commerce_bulk_invoice_block_view($block_name = '') {
    $block = array();
    if ($block_name == 'showinvoiceoptions') {
        $block['content'] = '
';
        if(!isset($_SESSION['selected_entities'])) {
            $block['content'] .= 'select a product first';
        } else {
            $block['content'] .= '
SESSION Variables:
';
            foreach($entity_array as $book) {
                $block['content'] .= '
';
                $block['content'] .= print_r( $book, true );
                $block['content'] .= '
';
            }
        }
        $block['content'] .= '
';

        $form = drupal_get_form('commerce_bulk_invoice_form');
        $block['content'] .= render($form);
    }
    return $block;
}


texts: How to make custom views exposed filter work with AJAX

texts:
I don't know how to make my custom exposed filter work with AJAX:
I have a view that has a contextual filter that filters for Node creation date by year. This filter gets filled via a query parameter like '?year=2021'.
Via the code below I have created a custom exposed filter form element to allow the user to select a year.
This works great unless AJAX is activated. How can I make this work with AJAX enabled?
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['#id']) && $form['#id'] == 'views-exposed-form-news-page-1') {

    $years = ['all' => t('- All -')];
    for ($i = date('Y'); $i >= '1997'; $i--) {
      $years[$i] = $i;
    }

    $form['year'] = [
      '#title' => new TranslatableMarkup('Year'),
      '#type' => 'select',
      '#options' => $years,
      '#size' => NULL,
      '#default_value' => 'all',
    ];

  }
}


texts: Administrator can add content for other users?

texts:
I have some users in admin/people.
Administrator can have the permission to view/edit/delete contents created by these users.
Is there any possibility: Administrator can add content for a user from administrator back end?

Or is this out of scope?
Thanks


texts: How do you map a Salesforce master detail field to a field?

texts:
I have successfully mapped all fields except company name which is a master-detail field in Salesforce. This field is required to make a record in Salesforce.
What field should be used to map to this type of data?


texts: When a Boolean property in ECK isn't added to the entity edit form, it is automatically unchecked. Why?

texts:
So I have an ECK entity type with a boolean property called "status", similar to the node "publish" boolean.
I use Page Manager to control what fields and properties will be loaded on the entity EDIT form.
Now it appears that if I don't show/load my boolean property form on the entity EDIT form AND if it was set previously to "checked" (1), after saving it now becomes "unchecked" (0).
I believe that shouldn't happen but I don't understand why it happens.
I don't want users to be able to tick or untick this checkbox when they update it.
Is this the normal behavior?


texts: ftp uploaded files are not in the library of Media module

texts:
I installed media module in Drupal 7 to browse the uploaded files on the server. I created a new field called media3 and this is its configuration.

This is the next page :

The problem is when I'm trying to add new content to this content type and select them in the library tab from media module, only the image files that are already uploaded through http protocol are displayed.

If I check the Allowed URI schemes checkbox, nothing will be displayed in the library tab.
 how do I can browse the ftp uploaded files? where they should be to be visible to media module?


texts: How do you rename the "save" comment button?

texts:
Does anyone know how to rename the "save" comment button? I am trying to change it to "Post".
I am using Drupal 7 and the Zen sub theme.


texts: Why entity_metadata_wrapper->save() doesn't update node's revision?

texts:
I'm developing a module to update nodes(enable revision). It looks like this.

 $nodes = node_load_multiple(array(), array('type' => $bundleType));
 foreach ($ndoes as $node){
    $w = entity_metadata_wrapper('node',$node);
    $w->MyFields->set($someValue);
    $w->save();
 }

It set fields correctly but node's revision-id didn't change after $w->save().

How can I update the revision ID?


texts:
I'd like to create a product list in drupal and send it in a webservice.
For this I created an entity type with paragraphs for each product.
How can I load the paragraph and access its fields? Until now I see only the target_id and target_revision_id of the product. Thanks!

$nodestorage = \Drupal::entityManager()->getStorage('node');
$productslist = $nodestorage->loadUnchanged(9)->toArray();
foreach($productslist['field_products'] as $prod) {
  debug($prod);
}

Result:

Array
(
  [target_id] => 1
  [target_revision_id] => 3
)


texts:
I am a complete newbie to Drupal, although I have many years of PHP development and even more years as a system administrator. My task is to move a few Drupal sites from CentOS 5.x/Drupal 6.x to Centos 6.x and Drupal 7.x

My plan is to move all sites to Centos 6.x and then upgrade to 7.x (if possible).

I downloaded the first drupal site using rsync and then I exported the relevant database with mysqldump.

I imported the database and created the appropriate mysql user with the same permissions as in the production server.

Important: In my local server I use the domain "testsite.local"
The production domain is "testsite.com".

Now, the problem: When I enter testsite.local in my browser, all I see is the Drupal page saying that I have not created a first page!

I am almost sure that this is a configuration problem, but I cannot pin-point it. Can you help me?


texts:
On page load I need to

show the toolbar on the left / in vertical mode when in admin theme
collapse/minimize the toolbar when in frontend theme

I'm looking for the event and the function to trigger those actions programmatically, e.g. something like

$(document).on('toolbar.loaded', Drupal.toolbar.setOrientationLeft);

and

$(document).on('toolbar.loaded', Drupal.toolbar.closeToolbar);

(I'm using the Admin Toolbar plugin)

Please note that I'm looking a solution that does not check CSS classes or triggers DOM clicks, in order to avoid timing problems due to asynchronous loading or exisiting toolbar settings.


texts: Using Adaptivetheme subtheme how to have fixed width left column?

texts: How do I have a fixed width left column and fluid right? At the moment, in my panels config there is only the fluid layouts available  e.g. AT Two column 33/66.


texts: How to remove readonly attribute from form input element

texts:
I have a form with date picker. Its a view exposed search form. i need to remove readonly attribute of this field to edit the field. I tried jQuery code jQuery("#edit-date-filter-value-datepicker-popup-0").attr("readonly", false); but didnt work. Can i do it in my view?

<input id="edit-date-filter-value-datepicker-popup-0" class="form-text hasDatepicker date-popup-init" type="text" maxlength="200" size="20" value="" name="date_filter[value][date]" placeholder="YYYY-MM-DD" readonly="readonly">


texts: What is wrong when Open atrium is installed with no colors and images?

texts:
I have successfully installed Open Atrium. Upon opening the site first time in the browser, i literally see no images, layouts of colors. Here is the screenshot:

I also have a series of warning messages being displayed as shown below:

Anyone has a clue, what's wrong really?


texts: Uninstalled modules still in system table?

texts: Right now I,m facing problem with high resource usage of my Drupal 6 website, I can't find the solution to solve the issue, when I checked the system table, uninstalled modules still in system table, Is this normal or not uninstalled properly.


texts: Change the content of a node programmatically with hook_node_view

texts:
I need to append some text programmatically before the text on the home page. But when I use hook_node_view(), I can't seem to do this with the following:

function general_node_view(&$node, $view_mode, $langcode) {
    if ($node->nid == 1) {
      //echo '<pre>' . print_r($node->body['und'][0]['value'],1) . '</pre>';
      $node->body['und'][0]['value'] = 'fdsf' .  $node->body['und'][0]['value'];
   }
 }

Am I going about this the wrong way?


texts: Views: Display the value of multiple value field as a separate column/field?

texts:
I have a multi value select list field in the content type.

In views it is currently displaying as:

title: test title
field_name: value1, value2, value3

And I want it to display it like this:

title: test title
key1: value1
key2: value2
key3: value3

Where field_name is the multi value field.
Any Idea?


texts:
I created a custom module which creates a content type (FAQs) with a paragraph field whose type is FAQ Item (with 2 fields, title and text).
After installing the module, I have a new content type as expected.
I add this new content type (which works), but when I want to add more paragraphs, I get this error.

edit start
↵An AJAX HTTP error occurred.↵HTTP Result Code: 200↵Debugging information follows.↵Path: /node/add/faq?ajax_form=1↵StatusText: OK↵ResponseText:

edit end
Is there any missing configuration the module should provide?
The YAML files are inside faq/config/optional. They have been created from the UI on another site and exported.
edit 2 start
My module files and structure

.info.yml file I have basic info link name, type, description, core_version_requirement and package.
.libraries.yml Am importing a JS file, inside "src-js"
.module is empty, without any php code.
.routing.yml also have basic stuff:
faq:
path: '/faqs'
defaults:
  _controller: 'Drupal\faq\Controller\GetFaqController::getFaq'
  _title: 'FAQs Page'
requirements:
  _permission: 'access content'

Inside config-optional folder I have my YML to create content type, fields and paragraph. Those .yml files I exported from another website where I create all of this and deleted "uuid" line.

Then in my controller I also have basic stuff (for now).
class GetFaqController extends ControllerBase {
public function getFaq() {

    echo '
FAQs
';

    return [
        '#title' => 'test'
    ];
}

}
This is my module structure/files.
Have very basic configs, that's why I am a bit lost with this error and what I search online I found same error but it is not related.
It seems something is missing with paragraphs and ajax request to add more.
edit 2 end
edit 3 start
I have created another module, this new module only creates a paragraph type with 2 fields (title and text), then I add manually this paragraph to "Article" content type and I get same error.
Another thing I have notice, in a clean drupal site with paragrpahs module installed, when I create a paragraph type manually via backoffice and then add it to any content type works correctly, when I install my module all paragraphs fields stop working and give this error.
If I uninstall my module and delete paragraph type created by my module, other paragraphs type start working again.
Here a repository of my custom module if someone want to test.
https://gitlab.com/drase15/custom-module
edit 3 end


texts: Inline entity form module fails when creating a new node and the reference method is Views

texts:
I have a Drupal 8, core version:8.8.x project, i'm using inline entity form module(latest version) for entity reference fields. Also i have tried using entity connect module but it caused various issues. The problem is when creating a new node, using the inline entity form and the reference method of field is Views: Filter by an entity reference view this error is coming up:

This entity (node: newNode) cannot be referenced.

How to reproduce:

Install inline entity form module
Create an entity reference field in any content type with Views: Filter by an entity reference view as reference method.
To your content type manage form display choose inline entity form - complex for widget.
Add new node for your content type, press add new node to your reference field, fill the modal form, publish it and press create new node(referenced node).
Lastly publish and save your node.

I tried some patches published to project issues but most of them are not applying at all. I would appreciate any ideas for solving it or suggestions for using a similar module.


texts: How can I alter the submit button text of bulk operations?

texts:
I'm trying to alter the text on the bulk operations submit button. It seems the standard hook_form_alter() does not work in this context.

The standard text is Apply to selected items and I want to change that for a particular view.

Code:

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-print-selected-pages-page-1') {
    // I can't find the button in $form.
  }
}

When I look at the generated source I can see that the bulk operations form has a form ID like views-exposed-form-print-selected-pages-page-1-asd1235x that changes between page reloads.


texts:
There is a module for increasing the node title, but how to increase the maximum length of a panel pane title?
I have a view pane which title must be overwritten in its panel pane settings. This works fine, but while appending extra tokens and styling to the title I bumped into the maximum length available.
How can this be changed?


texts: Add .active class when certain view is executed using hook_menu

texts: I have a view that is not related with a menu but I need to add .active class to an element of this menu when the view is shown. How can I alter the element adding a class active?


texts:
I would like to create rated inteterests for each user.
Until now what I have is a taxonomy term vocabulary defined and a field in the user account attached to this vocabulary.
Until here what a user can do is to check or not each term of the vocabulary, using the widget options_list.
What I would like to do is to let the user select the level (0-10) of preference for each term.

I've tried to create a custom field with two columns, tid and value, then linking each tid with taxonomy term in hook_field_widget_form, but no luck as I'm not an expert in fields, so I'm confused about how to implement:

/**
 * Implements hook_field_widget_form().
 */
function taxonomy_value_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $tids = isset($items[$delta]['tid']) ? $items[$delta]['tid'] : array();
  $values = isset($items[$delta]['value']) ? $items[$delta]['value'] : array();
  $element += array(
    '#delta' => $delta,
  );

  switch ($instance['widget']['type']) {

    case 'taxonomy_value_widget':
      if ($vocabulary = taxonomy_vocabulary_machine_name_load('tags')) {
        if ($terms = taxonomy_get_tree($vocabulary->vid)) {
          foreach ($terms as $term) {
            if ($term->depth == 0) {
              $element[$term->tid] = array(
                '#markup'  => '
' . $term->name . '',
              );
            } else {
              $element[$term->tid]['term'] = array(
                '#markup'  => '
' . $term->name,
              );

              $element[$term->tid]['tid'] = array(
                '#type'          => 'value',
                '#value'         => $term->tid,
              );

              $element[$term->tid]['value'] = array(
                '#type'          => 'textfield',
                '#value'         => in_array($term->tid, $values) ? $values[$term->tid] : 5,
              );

            }
          }
        }
      }

      break;
  }

  return $element;
}


texts:
I'm getting error

Drupal\Core\Database\DatabaseExceptionWrapper</em>: SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;map.sourceid2&#039; in &#039;field list&#039;: SELECT map.sourceid1 AS sourceid1, map.sourceid2 AS sourceid2, map.destid1 AS destid1

when trying to use two value ids in migrate yml file:

id: recipe_daily
label: Recipes
migration_group: recipe
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls:
    - http://mysource.com/data
  item_selector: /recipes/recipe

  fields:
    -
      name: text
      label: 'Text'
      selector: text
    -
      name: title
      label: 'Title'
      selector: title
    -
      name: recipe_day
      label: 'Day'
      selector: '@day'
    -
      name: recipe_id
      label: 'Recipe id'
      selector: 'detail/@id'

  ids:
    title:
      type: string
    recipe_id:
      type: string

destination:
  plugin: entity:node

process:

  type:
    plugin: default_value
    default_value: recipe_daily

  title: title
  text: text

dependencies:
  enforced:
    module:
      - recipe

Since it's called ids I assume it takes multiple values but cannot find any examples anywhere. Any ideas much appreciated


texts:
As we see in facebook, that it can detect & tag persons within a picture. Is there any way to achieve this from Drupal? any module exist?

The main purpose is to verify each user account- so everybody has only one account. Lots of country people don't have any National ID/passport. So, how can we trace their unique identification? Mobile number is a way, bt one person can have multiple numbers.

OR, is there any way, we can scan finger print as iphone6 has that built-in function........

I know i'm asking for too much,,bt I already need that kinda stuff in job :(

Any suggestions are welcome .....please


texts:
I noticed that users are able to log in via /user/login/[any random characters], thanks to a comment on a previous post of mine about users not being able to log in some times.

Is there a way to add the random:integer token to the log in URL? I tried simply creating a link to /user/login/[random:integer] but that didn't work; it generated exactly that link in the browser.


texts: How to get selected value in option id value in drupal form api

texts:
Hi hello please help how to get dynamically selected option id value (i.e #options=>0=>'bala',1=>'kumar')

for example (1001->india,1002->usa) like that stored in select option value (india, usa like that) , but i want to fetch the id value(1001, 1002) of selected value of id value from option? that value to be store in $key variable, please help me

$query_state=db_select('state', 's');
$query_state->fields('s',array('State_code','State_name'));
$query_state->orderBy('State_name','ASC');
$state_results = $query_state->execute();
$options_state = array();

foreach($state_results as $state_record) {
  $options_state[$state_record->State_name]=t($state_record->State_code);
}

$form['state1']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

// here values are popup in select option component but corresponding value of state in city select option not visible

 $key = !empty($form_state['values']['state1']) ? $form_state['values']['state1'] : 1;

$query_city=db_select('city', 'c');
$query_city->fields('c',array('District_Code','District_Name','State_Code'));
$query_city->condition('State_Code',$key,'=');

$query_city->orderBy('District_Name','ASC');
$city_results = $query_city->execute();
$options_city = array();

foreach ($city_results as $city_record) {
  $options_city[$city_record->District_Code]=t($city_record->District_Name);
}

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '
',
  '#suffix' => '
',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state1"]' => array(
          'value' => $options_state,
      ),
    ),
  ),
);

function _ajaxfunction($form, $form_state) {
  return $form['city'];
}


texts: Filter values of a cck field with a view

texts:
When I create a new node of a certain type, I would like to filter a certain field depending on a view. For example I would like to filter through the top 3 latest news stories (as the view will filter though a news story content type which will display the 3 latest news story only so the sort criteria would be by the date).

Thanks in advance!


texts: JavaScript behaviours don't run on first page load after clearing cache

texts:
Refresh the page again, however, and all behaviours function as they should. Why?

(function ($) {

console.log('This console.log runs');

Drupal.behaviors.endlessUniform = {
    attach: function (context) {

        console.log('This console.log does not run');

        $(function () {
            $("select").uniform();
        });
    }
}
})(jQuery);

My JS file runs the first time the page is loaded after flushing the cache, however, anything inside a drupal behaviour does not. Refresh the page and load it a second time after flushing the cache and the behaviours function as expected.


texts: Drupal 7 multistep form submits user_register_submit handler to early

texts:
After two days of searching and debugging I decided to give up and ask help here...

I'm building a multistep form in Drupal 7 with 4 steps. The user_register_form is in the second step.
For building this multistep form I used the help of http://www.grasmash.com/article/building-multistep-registration-form-drupal-7. I also did some modifications so other modules that alters the user_register_form would be called. I used the modification from comment http://www.grasmash.com/comment/127#comment-127.

My problem:
After submitting the second step, the user_register_submit() function is being called. Although it should move all submit handlers to the $form['next']['#submit'] and call all submit handlers after the last step.

I tried to unravel the whole form handling within Drupal and explore every single function used. I found out that somehow the #submit handler ends up in 'triggering_element', which causes the form to fire the submit handlers directly after step 2 instead of 4 ... but can't figure out how and when this element is set.

Any ideas where to look, or how to investigate this more or better?

Edit:
After better reading I came to the conclusion that the way the multi step from grasmash works, is aimed to execute the submit handlers after every step. Although I thought that the submit handlers were moved to $form['next'] so they could be executed in the end.
So now I'm wondering how to change the code so all submit handlers will be executed after the last step?


texts: How to display taxonomy terms of a particular vocabulary in views

texts: I am trying to display taxonomy terms of a particular vocabulary in views terms field, but I am lost as to how to do it. I have done the same thing in full view mode using template.php.


texts:
Seems so elementary but how does one get the active state onto the
 of a link when manually using the l() function?

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>

The above of course outputs the link in a list item with an active class on the link if the page is current, but how do I get that class onto the
?


texts: Moving from subdomain to top level, link/image paths incorrect after manual edit

texts:
TL;DR Filepaths contain old subdomain prefix after find replace database and site code, can't determine cause.

I have a hosted site on mywebsite.com/drupal, I want to move it to my computer localhost.

I have a LAMP stack and I compress and download the contents of mywebsite.com/drupal and export its mysql database, mydb.sql, using phpmyadmin.

I uncompress and place all the files from mywebsite.com/drupal in /var/www/html/, I create a new database, local.db, locally and import mydb.sql. I edit /var/www/html/sites/default/settings.php $databases array and connect it to local.db.

I ensure all files permissions are correct by running

chown user:user -R /var/www/html/
chmod -R 755 /var/www/html/

I can then access my site using a browser and going to localhost, however the images are missing none of the links work.

Initially I thought the cause was that there are many instances in the database and my site code still containing filepaths with the subdomain /drupal/ prefix, images for example:

src="/drupal/sites/default/files/inline-images..."

When I move the site to localhost, it should just be:

src="/sites/default/files/inline-images..."

To solve this, I did a find /drupal/ and replace / in my database, reimported it and then used grep -rl '/drupal/' ./ | xargs sed -i 's_/drupal/_/_g' on /var/www/html/.

I thought this would have resolved the problem, however when I access localhost, the problem persists, images and links still contain the /drupal/ prefix in their filepaths. I've read on a few migration guides that I should flush all caches on the drupal backend before moving  (which I did) and also potentially flush the mysql cache using phpmyadmin, however I get an error #1146 - Table 'mydb.cache' doesn't exist when I try to execute the truncate commands.

Other guides mention .htaccess, which I copied over from mysite.com/drupal, admittedly I don't understand everything inside it deeply, but I can't find any code which is prefixing filepaths with /drupal/.

As a sanity check, I created /var/www/html/drupal/ and copied my site and then everything works fine.

I don't understand, how can the filepaths remain the same when I have changed all instances in the database and site code? I think there is something easy I'm missing but I can't figure it out.


texts: better exposed filters and bootstrap 3. Problems with alignment

texts:
I have Drupal 7 and the BEF to filter a view. My site is running the Drupal Bootstrap framework V3. The regular 'basic' theming for the exposed filters works, but I would like to use checkboxes and the JQuery slider.

I have a problem with the formatting on check-boxes and sliders.

I've googled it, but didn't find anything relevant.

Thanks in advance


texts: Drupal 7, Dev Site, will not Aggregate Javascript or CSS

texts:
I have two installations of the same site. The first is sub.website.com, and is the main website. The second is sub.website.com/drupaldev.  On the /drupaldev site I cannot get the javascript or CSS to aggregate, which is causing myriad odd problems. I have checked the tmp directory, changed it, modified permissions and re-installed the site from scratch. None of these things has allowed me to get the website to aggregate.

Is the problem that I am hosting the development site as a folder of the main site?


texts: How handle large number of images in gallery node Drupal 7

texts:
I have some gallery nodes with a large number of images (100+), the upload with Plupload integration module works fine, but after save the node and edit it again the node edit form loads 20+ seconds! How can I reduce the loading time of the form? Somebody have any suggestion for this problem? Lazy Loading of Fields possible? Pagination? Some Module?

Thanks


texts:
I have a form that's built via the FormAPI (admin UI) from an entity that has been created via a module. In the module, I have a hook_theme() setup that tells the system to use the template provided with the module.
item_types_theme() {
  $theme = [];
  $theme['add_copy'] = [
    'template' => 'forms/add_copy',
    'render element' => 'form',
  ];
}

I then have a custom theme, and I am trying to get the custom theme to override the default template provided by the module:
function lms_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'form__' . str_replace('-','_', $variables['element']['#id']);
}

This didn't give me access to {{ form }} so I added this:
hook_preprocess_form():
function lms_preprocess_form(array &$variables) {
  unset($variables['children']);
  $variables['form'] = $variables['element'];
}

and I now have access to {{ form }} but the elements don't appear to be correct, as I cannot use |without in it to exclude form fields. It's also not behaving correctly, because I can do
{{ form.delete|without('confirmation') }}

and the confirmation markup won't display (Neither will the rest of the form, except for the elements inside of the delete container), but if I do
{{ form|without('delete') }}, {{ form|without('delete','confirmation') }} or {{ form|without('delete.confirmation') }} Nothing happens (the fields and the 'delete' container still render).
I don't think I am passing stuff into the theme correctly, even though the new template is actually being loaded. {{ children }} is the default variable used in that template, so I am trying to figure out what I am doing wrong.
There is a patch on the drupal.org forums that apparently fixes nested arrays for use with |without(), but it makes matters worse for me when I apply the patch in that if I use without at any point, it stops the entire form from rendering.
I can verify that the original form, located at my_module/templates/forms/add_copy.html.twig allows me to use |without() but the new template located at my_theme/temates/form/form--add-copy.html.twig does not.


texts: How to remove a page from a books and/or delete a book?

texts:
I placed a basic page into a book but now want it removed from every book. In the book outline settings I only see a way to move it to another book, I see no option to set it to none. I also don't see a way to delete a book in structure/books.

One option I've considered is uninstalling the book module and reenabling it but I'd rather not lose every book I have because of one page.

Is there a way to remove a page from a book, and/or delete a book without uninstalling the book module?


texts: How can I stop JavaScript from being cached during development?

texts:
I have a Drupal 8.00-beta11 site and am trying to dynamically add JS to a page, so that I don't have to clear the cache every time I edit the JS file. I have a custom module (lets call it my_module) in drupal_root/modules. My javascript file is in drupal_root/modules/my_module/js/my_js.js.

I have a my_module.libraries.yml file as follows:

my_module:
  version: 1.x
  js:
    js/my_js.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui

In my my_module.info.yml I have:

name: My Module
type: module
description: ...
core: 8.x
libraries:
  - my_module/my_module
package: Custom
version: 0.1

This loads the JS succesfully, but I need to clear the cache everytime after I edit it to see the changes.

In order to avoid doing this, I added the following to my buildForm function:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my_module') . 'js/my_js.js',
);

$form['#attached']['library'][] = 'my_module/my_module';

I also placed the following in drupal_root/modules/my_module/my_module.module:

<?php

  function grid_tools_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_module/my_module';
  }

  function grid_tools_page_build(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_module/my_module';
    $path = drupal_get_path('module', 'my_module');
  // Add JavaScript/CSS assets to all pages.
  // @see drupal_process_attached()
    $attachments['#attached']['js'][$path . '/js/my_js.js'];
  }

?>

However, none of this has worked and I still need to clear the cache to see my changes. How do I avoid having to clear the cache every time?


texts:
I try to use "DrupalDateTime" class in my theme to show native date and time in custom format based on special TimeZone in my nodes.
According to this article: New Datetime API

Drupal core and contributed modules should use the DrupalDateTime
class in preference to the PHP DateTime class or to functions like
date(), gmdate(), strtotime(), etc.
the class incorporates the IntlDateFormatter into its format() method,
if the IntlDateFormatter is available, and otherwise falls back to
wrapping formatted output with Drupal's translation system. The
IntlDateFormatter requires additional information, which can be passed
in a settings array.

And then I add below code to MyThmeName.theme:
Note: Be sure to add use Drupal\Core\Datetime\DrupalDateTime; at the top of any files that use this class.
function MyThemeName_preprocess_node(&$variables){
  $node_date = $variables['node']->getCreatedTime();
  $date = new DrupalDateTime($node_date, 'UTC');
  $date->setTimezone(new \DateTimeZone('Asia/Tehran'));
  $variables['date'] = $date->format('Y/m/d'); }

I'm sure PHP intl extension was exist! I cleared comment before this line in php.ini file:
;extension=php_intl.dll

I get below error:
Exception: DateTime object not set. in Drupal\Component\Datetime\DateTimePlus->__call() (line 308 of core\lib\Drupal\Component\Datetime\DateTimePlus.php).

Update:
I'm following kiamlaluno solution carefully
but the result not changed and date is shown in the English language yet and howsoever I try I can't get an appropriate result to show date and time in my native calendar, where is the problem, is there other parameters that should be set.
if (isset($variables['node'])) {
  $date = DrupalDateTime::createFromTimestamp($variables['node']->getCreatedTime(), new \DateTimeZone('Asia/Tehran'), ['langcode' => 'fa']);
  $variables['date'] = $date->format('Y/m/d');
}

Thanks for any help.


texts: Cannot import database. An error occuring in wamp server

texts:
I am using Drupal.  I export the sql database from the wamp server and make a new database where I am importing it.  It's approx 6 MB. I increase the upload_max_size and clear the cache before exporting, but this error is occurring. Then what I do

SQL query:

INSERT INTO cache_menu (cid, data, expire, created, serialized) VALUES ('links:management:tree-data:en:.......


texts: how to use css sprite in all my pages ( menu+ views)

texts:
i have a page contain view and menu and i want to use same icon  for both,
so i made a sprite image but i don't know how to use it in 2 different classes?

Any help with this would be much appreciated.

Cheers in advance.


texts: db_query with where clause not returning anything

texts:
I ran following query on DB through PHPmyAdmin

SELECT * FROM field_data_field_country_feed WHERE entity_id=40848

And it worked and returned me the single row
But when I try to implement that in my custom services it is not returning anything.

$result1 = db_query("SELECT * FROM field_data_field_country_feed WHERE entity_id=40848")->fetchAll();
        var_dump($result1);

Please help


texts: How to translate the author line "Submitted by ... on ..."

texts:
I've created a custom content type in Drupal 8.9.1. Each content post automatically renders the line
Submitted by author_name on 08.07.2020 - 18:21

Even though my Drupal system language is set to German, I cannot find a way to show a translated version of this "submitted by" text.
When I check the translations page under /admin/config/regional/content-language I also see a correct translation for the segment ("Geschrieben von"). But there's no indicator how this is mapped to the actual English value.

I've also seen posts saying that you have to do that manually in the Node Template. But I have not found such template and guess the approach has changed after Drupal 7.


texts: Is it possible to index custom page content?

texts:
I have created certain pages and blocks using web services programmatically.The content of those pages is fetched from outside the existing Drupal installation and they are not getting indexed in search results.

Is it possible to index my custom page titles and links in the search results? Or is there any other way to do this?


texts: How to modify form fields before validation

texts:
I have a custom content type with a lot of fields, and some are required.
Under some circustances these required fields can be computed from other fields.
I tried to use also hook_node_validate, but i have always the error message because the field is empty when the user sends the form.
It's not easy to implement a javascript solution, since the algorithm to compute the values is not trivial.
Which kind of solution do you suggest to use?


texts:
I am working on a site using wysiwyg-7.x-2.2, media-7.x-2.0-alpha3 and ckeditor-4.3 as library
on drupal core 7.24.

The problem is:
If I put a link on an image in the wysiwyg editor, it doesn't get remembered. That means if I press "Disable Rich-Text" it hasn't been added and it will not get posted on save.
I can make a stand alone link and a add a stand alone image.
If I manually add the a tag to the image it CAN get saved.

Any ideas for a fix?


texts: View Datasource - generate URL to Thumb and Full image

texts:
I am trying to create a view to generate JSON Data. Therefore I am using the "Views Datasource" module. All in all the view is a list of files (File Entities) and actually look like this:

{"nodes":[{
    "node":{
        "filename":"xxxx.jpg",
        "rendered":"",
        "uri":"public:\/\/media\/img\/[...]\/xxxx.jpg"}
    },
    ...
]}

But what I really want to have is a list of nodes, including the web url to a thumbnail and another to a bigger version like that:

node: {
    "filename": "xxxx.jpg",
    "url-thmb": "http://.../xxxx.jpg",
    "url-full": "media/.../xxxx.jpg"
}

In this Situation it does not matter if the path to the file is absolute or not and the name of the keys in the json object, either.

Right now the Settings of the view are:

Display: Files,
Format: JSON Data document - simple
Fields:

#1: File: Name

#2: File: Rendered

#3: File: Path

Thanks ahead for any Help!


texts: How to set non Drupal 404 and 403 pages for Drupal?

texts:
Under Site Information we can provide custom 404 and 403 pages to Drupal, but these need to be created inside Drupal, and non Drupal pages are rejected. (such as myerror/404.html).

Contrib modules like custom error and static 404 also work inside Drupal. Any ideas on how to set an external page as 404 or 403?


texts: How to change the Add another item button text for a multivalued field?

texts:
I have tried with this in template_preprocess_input

function mymodule_preprocess_input(&$variables) {
  $element = $variables['element'];
  if (!empty($element['#name']) && $element['#name'] == 'myfield') {
      $variables['element']['#attributes']['value'] = t('Add another period');
      $variables['element']['#value'] = t('Add another period');
  }
}

But this is not working. Is there any other method?


texts: Superfish Menu links disappear on iOS (only if they have dropdown menus)

texts:
I've got a superfish menu as the main menu on my site. Two of the links in the menu have sub-links and are presented as a drop-down, hover menu. This works great on desktop browsers. On iOS, however, the main link disappears if that menu item has a drop down. It's only gone in the default state though, if I tap on the spot where it should be, the link shows up again and the drop-down menu appears as it should. If I tap the other link which has a drop down menu, the first drop down will disappear and so will the main link. For example, if the normal menu looks like this..

FOO BAR BAZ BAT

and BAR has a drop down menu, then the menu will look like this on iOS:

FOO <empty space> BAZ BAT

but if I tap on that empty space, then BAR will show up and so will the drop-down menu.

I've checked the CSS and don't see any differences in the styles.

I'm sorry I can't give you a link to the site to see where this is happening. I'm under an NDA and the site isn't public yet.

EDIT: I discovered that the css sets .sf-menu li to have position: relative. When I disable this rule in the inspector, then BAR appears in the spot where it should be. However, when I do this, the drop-down menus no longer have the correct context for their positioning. So, I need this rule so the drop-downs work properly, but something about that rule is causing those elements to jump out of position.

So, two questions:

1) Do you know why this is happening and do you know of a fix?

2) or, do you know of a way to make them non-drop downs when iOS is detected? The dropdowns are not crucial to my site navigation.


texts: How can I allow front end users to add their own custom fields?

texts:
We have a new project that is going to allow users to add their own nodes of a content type e.g. 'cars'.

There are some existing fields that they need to complete e.g. 'colour' and 'year'. We also need to allow them to add their own custom fields, which only they can use. So one user will add 'mileage' whereas another might want to add 'number of seats'. How would I go about allowing hundreds of users to do this without bloating the content type?

We will be building it in Drupal 7.

Thanks for any help.


texts:
In one instance we are using a webform to create a form and it uses field type 'date'. The end result looks like this:

I would like to mimic this, but in a custom form. Currently what I have is:

Code:

 $form['date_starting'] = array(
  '#type' => 'date_select',
  '#title' => t('Starting'),
  '#date_label_position' => 'within',
  '#date_format' => 'm d Y',
  );


texts: Redirect After Creating a Node - bootstrap.inc

texts:
I wanted to create a node from a standalone php file bootstrapping drupal.
I printed out the form and it creates a node perfectly but it doesn't redirect to the created page or any other page for that-matter.

i would be grateful if someone points me to how to achieve that. I tried to use hook_alter_form but i can't get it to work

this is what i am using now

<?php

define('DRUPAL_ROOT', '/home/xxx/public_html/am');
$_SERVER['HTTP_HOST'] = 'xxx.com';

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

module_load_include('inc', 'node', 'node.pages');

?>

<?php
$form = node_add('user_submited');
print drupal_render($form);

?>

ps. One of the reasons i wanted the form to load fast, currently in my theme  its about 200kb with 21 requests to load the form creation page, now its about 4kb with 3 requests .


texts: Views Configure contextual filter by user's country

texts:
Drupal 7, commerce kickstart2.

Need to create a view with ContentType ProductDisplay. ProductDisplay has field Product. A Product has multiple field of a Country type.

User object has a property Country filed by IP2Country Module. The view need to show only products with user’s country.

View: type=page, link= /products (no other arguments in url expected), added releation Product

Here what I tried

Created Contextual filter: "Product: Country List (indexed)". Had to add index to this field so it can be select in contextual filter
Configured default argument for the "When the filter value is NOT in the URL". By using "hook_views_plugins" created "Current user's Country name" argument type. It is working and providing correct argument value  - user’s country

Didn’t manage to make it work. Also, tried some other things and spent few hours browsing web for a possible solution. Didn't find any similar problems or solution. There’re many examples with taxonomy terms and url args.

As a plan B,  think to create view for every country and override main view, but don't like it

Is a better solution to the task possible?

Thanks!


texts: Node add form alter & submit custom field

texts:
I have a content type "event" with a field called "field_pricelist". It's a dropdown with no values, I add the values when I alter the form. The values come from a custom table (install / schema) in my database. I want to save this custom value on insert/update. My code works but I don't think it's the best way to save/update a custom field.. Any suggestions?

function TableManager_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'event_node_form') {

global $user;
$query = db_select('pricelist', 'p');
$query->fields('p');
$query->condition('user_id', $user->uid,'=');
$results = $query->execute()->fetchAll();

$query2 = db_select('field_data_field_pricelist', 'd');
$query2->fields('d');
$query2->condition('entity_id', $form['nid']['#value'],'=');
$results2 = $query2->execute()->fetchAll();

$dropdown_array = array();
foreach ($results as $r) {
    $form['field_pricelist']['und']['#options'][$r->pricelist_id] = $r->pricelist_name;
}
$form['field_pricelist']['und']['#default_value']['0'] = $results2['0']->field_pricelist_value;
$form['#submit'][] = "TableManager_form_submit";
}

}

function TableManager_form_submit($form, &$form_state) {

global $user;

$nid = $form_state['values']['nid'];
$pricelist_id = $form_state['values']['field_pricelist']['und']['0']['value'];

$query = db_update('field_data_field_pricelist');// Table name no longer needs {}
$query->fields(array('field_pricelist_value' => $pricelist_id));
$query->condition('entity_id', $nid, '=');
$query->execute();
}


texts:
I'd like to emphasize a character in the Taxonomy Term Name field. Text format is Filtered HTML, but the name (=title) is being displayed like this:

AK ORDERED SETS, N-UPLES, ORDERED ALGEBRAIC STRUCTURES

Any ideas?

Thank you very much!


texts:
How do I convert SELECT title , SUBSTRING(title,13,4) as num FROM node_field_data ORDER BY ABS(num) to the format for Drupal 8?

I tried this code.

 $query = $db->select('node_field_data', 'nfd')
  ->extend('\Drupal\Core\Database\Query\TableSortExtender')
  ->extend('\Drupal\Core\Database\Query\PagerSelectExtender');
  $query->limit('50');
  $query->fields('nfd',array('title',substring(title,13,4) as num,'changed','nid'));
 ->orderBy('num', 'ASC')


texts: Why do I get the "could not find the controller" error?

texts:
I'm trying to setup DrupalGap with Commerce following this tutorial, but I get this error:

  404 not found: could not find the controller.

I've manually confirmed Services are set up properly with Advanced REST client (Chrome), with this instructions. All seems OK; the endpoint/resource is operating and I receive a 200 OK response, but when I try to test the application from admin/config/services/drupalgap, I always get this error.

I use Services frequently and I can confirm It's working good on this site. I also verified DrupalGap is working too.

What could it be?


texts: D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path

texts:
My file directories have not changed, but every time I move from local host to production, or just change the filename of a test site online, I loose the images.

For example if I use the backup of prodcution server in local I am getting the path name like below:

  http://localhost/sites/all/sites/default/files/images/image_name.jpg

here the project name is missing. thats why I am not getting the images.

I have changed the base_url in local as

  http://localhost/project-name

But even that doesn't helps. (Cleared the cache after changing)

Merely this is a duplicate of this question

But I didn't get what I need on that question. Thats why I reposted again.

Any help will be thankful and grateful...


texts: How do I check if the site is in maintenance mode?

texts: How do I call MaintenanceMode::applies(RouteMatchInterface $route_match) from hook_theme_suggestions_page()?


texts: "Is all of" view search doesn't work with the module "Better exposed filter"

texts:
Drupal version :  8.2.0
Module "Better exposed filter" version :
8.x-3.0-alpha1

In short :

I created a view with an exposed filter. When I use the operator "is all of" from my exposed filter, all works. My exposed filter shows some tags in a select/option html list. I downloaded and installed the module "Better exposed filter" for display my exposed filter in checkbox instead the select/option html list. If I configure my exposed filter for it display checkboxs, then the view displays no result.

In detail :

I created 3 simples contents of type 'articles' :

Recipe one (tags 'ingredients' : salt, sugar )
Recipe two (tags 'ingredients' : super, pepper )
Recipe three (tags 'ingredients' : pepper, salt )

I created a very simple view :

When I do a search, I get two of my articles if I select the tag "sugar" with the exposed operator "is all off" : (look the Query, only one "INNER JOIN")

Tags exposed filter is an html select/option list. I want to change this style by a list of checkboxs. So, I configure the filter style with the "better exposed filter" module :

When I do that, my view works when I search with the filter exposed operator "is one of". But when I use the filter exposed operator "is all off", no result displayed !

In the new query, I noticed there are two "INNER JOIN". The second uses an id = 0, the error must be here.

My questions are :

Do I forget something in my configuration ?
Is a bug in the module "better exposed filter" ?
What should I do to operate the operand "is one off" when I display it in list of checkboxs ?


texts: Content for textgroup views is not allowed for translation because of its text format

texts:
I have this problem with a view's header. I am allowed to enter a translation but the translated text is not rendered when the view is displayed in that language.
I have the following warning in the Views interface.

content for textgroup views is not allowed for translation because of its text format

I read other posts suggesting to visit Configuration » Regional and language » Multilingual settings and verify the text format is selected. These posts were addressing the problem for blocks and they didn't solve my problem.
Any similar experience or solution?


texts: Override formatting for paragraph edit view

texts:
I have a paragraph type defined as two fields, which are Person and Role.

I can customize the structure of the paragraph fine to view. However, I am stuck in editing how the form elements sit in the Edit screen.

Debugging the twig files indicates that the Theme Hook around these components is 'container' and not anything to do with 'paragraph'.

Is there either:
a. A way to specify a 'container.html.twig' file to render the paragraph's form?
b. A way to specify how the paragraph should render forms?

Is there something else I may have missed?


texts: How to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment

texts:
I have written my first deployment_module for a Drupal 7 site and installed it into a virtual host on my development server.

I would like to check to see if my hook_update_N() functions have been invoked correctly and so am wondering how to determine which is the latest hook_update_N() function invoked in a Drupal 7 environment.

I imagine some Drush command would be easiest way to find out. Failing that, it is probably set in the database somewhere.

Any ideas?


texts:
In relation to Drupal 8 ... if a user wanted to create a link such as the following:

link

How could such a link be created, normally creating a link requires the use of the Url object and so the symbol '#' can't normally be used, nor can 'javascript:void (0)'.

Essentially I'm trying to create an link with an anchor tag in it.

Thanks.


texts:
I have seen the OA webinar on extending Open Atrium that documented how to make custom content types for sections and have them be recognized and tie in to the OA hierarchy. I would like to do the same but with spaces.

I can clone the space content type to get different ones like "department" or "project" with different custom fields but I want them treated separately in the navbar/breadcrumb.  In other words, the label "space" isn't useful - can't sell that to my client.  Having departments and projects all lumped together as spaces is awkward and too generic.

As far as I can see spaces are OG groups and you can make custom OG groups, but OA builds a complex hierarchy with permissions inheritances and such so not sure if it's possible.

The label "space" and such are hardcoded into the oa breadcrumb module so it appears there's no flexibility and this may require substantial rejiggering of the architecture.

Is there a way to override the default breadcrumb toolbar using the Panels Breadcrumb module (part of the OA distro)?  Can I just roll my own navbar and disable the oa specific module?


texts: hook_node_presave() fired twice when adding new node

texts:
I've just noticed that hook_node_presave($node) is fired twice when adding new nodes: Once it's called from node_form_submit(); the second time from entity_save().
It turns out that $node->nid is not set in first call, but it is already present in the second one.

Is this a normal behavior for hook_node_presave($node) in Drupal 7? Does the node containing node reference fields make a difference?


texts: How to use Views 3 API to display custom tables?

texts: I have some custom tables in the Drupal Database which are not of any content types. I want to use Views to display the values from the tables on to the website. Is there a way or a module that already provides this functionality? I am using Drupal 7 and Views 3 API.


texts: Create nested paragraphs programmatically

texts:
Similar to the question here but for D8. I've managed to create the child paragraphs but failing to generate the parent paragraphs and attaching the child to them.

$questions = [];

foreach($data['questions'] as $question) {
    $answers = [];
    foreach($question['answers'] as $answer) {
        $correct = $answer['field_correct'] === 'Yes' ? 1 : 0;

        $answers[] = Paragraph::create([
            'type' => 'quiz_answers',
            'field_answer' => $answer['field_answer'],
            'field_correct' => $correct,
        ])->save();
    }

    $questions[] = Paragraph::create([
        'type' => 'quiz_question',
        'field_question' => $question['field_question'],
        'field_answers' => $answers,
    ])->save();
}

$new_submission = Node::create([
    'type' => 'quiz_submissions',
    'title' => 'Quiz Submission',
    'field_quiz' => $data['quizID'],
    'field_question_submission' => $questions,
]);


texts: How do I export the list of URL alias into an excel or csv?

texts:
I am beginner and have recently started to work on Drupal website that has been implemented at my work place.

I would like to export the list of URL alias to an excel or csv file so that we can look at the various url aliases that we have set and eliminate or update those that aren't required.

How can I achieve this?


texts: how to apply .active class to only one menu item that uses optional filters

texts:
I have an exposed a filter to a page like so in drupal: http:example.com/user?profile=12 There is a menu entry for this specific link in a block in the sidebar. Is there a way drupal can add the .active class to the link with this specific url. Currently the active class is applied to links with this pattern: http://example.com/user?profile*

Which happen to be all links in that block.


texts: how to create a field collection while content type creation programmatically?

texts:
I want to create a field collection to group two fields in a content type programmatically so that when the user installs the module, the module installs the content type and let the user create content through 'Add Content' option .

I have created the field using field_create_field function in HOOK_install. I have created two fields and field collection. I dont know how to link the field collection with the two fields. I have searched over forum and I came across various materials just explaining how to add,edit and delete values of field collection programmactically but I could not find any useful information on how to create field collection in content type. Any help on this topic will be much appreciated.

In my code to create the content type with the field collection,the content type is created well with the field collection but when I check in the structures -> field Collection -> field_group->manage field, The fields are not getting displayed there and when I go to 'add content' the field collection does not have those fields but the fields are displayed outside the field collection container


texts: How to count the node of content type for corresponding entity reference field

texts:
I am creating a report. I want to count the nodes of a content type saved for particular entity reference field.

So far I have worked with Views Aggregator and Forena Reports.

But I am not able find it. Can anyone help me on this please?


texts:
I'm using the awesome Internationalization Module for managing the translations of my multilingual website. The name of each menu item also becomes the page title (the HTML TITLE tags). When switching languages everything works perfectly except the page titles. The page title shows correctly the name of the page, but in the LAST language I translated that menu link into. The last added translation of the menu is Chinese, so the page titles are always Chinese, regardless wheter you are on the Swedish or French version of that page.

Using Drupal 7.18
Using Internationalization module 7.x-1.7, fully enabled.
The multilingual options of the menu are set to 'Translate and Localize. Menu items with language will allow translations. Menu items without language will be localized.'

What could I try to fix this?


texts: Autofilling fields based on another field

texts:
I have a very complex situation where I need some advice. I have a content type my_content, which has a field collection field attached to it field_mycollection, which has an entity reference field referencing to user field_my_userreference, a phone field field_my_phone, a text field field_my_text, and another text field field_my_anothertext.

My Content
|_ field_mycollection
   |_ field_my_userreference
   |_ field_my_phone
   |_ field_my_text
   |_ field_my_anothertext

The user entity has also have fields field_my_phone, field_my_text and field_my_yetanothertext which the latter has a different machine name.

What I want to do, if in my_content edit/add form, in field_my_userreference a user is selected, the other fields should be auto-populated from the selected user's data. The auto-populated fields should still be editable.

How could I achieve this goal? I'd like to do it, if possible, with some coding, using hook_form_FORM_ID_alter().


texts: file_field_widget_form error when programatically creating nodes

texts:
I have a simple routine which I use to create nodes. The logic is something like this:

function make_node($node_type, $field_data) {
    foreach ($field_data as $k => $detail) {
        $field_key = _get_field_keys('field_' . $k);
        $field_key = $field_key[0];

        $node -> {'field_' . $k}[$node -> language][0][$field_key] = $detail;
        $form_state['values']['field_' . $k] = $detail;
    }
}

Then I run drupal_form_submit and it returns any errors from that and everything is great.

I'm having an issue with creating nodes which have a file upload field which uses the file u widget. I get the error:

Notice: Undefined offset: 0 in file_field_widget_form()

I had a look at the offending line (line 511 of modules/file/file.field.inc) and I can see why it occurs, the function file_field_widget_form has an argument called $element, which is supposed to have an index 0, but when I set up the form programatically, that index is not set up.

When I make a node of the same type using the web interface, I can see that the $elements array is set up with the 0 index before even submitting the form.

How do I rectify this issue, do I need to call something else before making my form programatically? I'm using Drupal 7 if it helps.


texts: How to theme form elements in a custom field widget?

texts:
I'm creating a custom telephone field and I'm a bit confused at how to go about theming the widget.

I have four elements in my implementation of hook_field_widget_form()...

A dropdown for the phone type, (i.e - phone, fax, toll-free).
A textfield for the phone number.
A textfield for the extension with the prefix "ext".
A checkbox to flag the number as the primary number, (the field has unlimited cardinality).

Functionally, the field is working great. It is saving the data in the database just how I would like. What I'm not figuring out is how to display the elements inline on the edit form. Right now, the form for the field looks like this...

I would like each of the elements to display inline. If I could just add a class to the div that wraps each of the elements, I'd be good to go. The closest that I've come is to add a class in my implementation of hook_field_widget_form() to each of the elements, but that adds it to the element and not the wrapper div.

I have a feeling I'm going to need to implement a theme function or a template file, but I just don't know where to start. All the information that I find about theme functions and template files seem to be about what the elements look like rendered on the page, and not about what the form elements look like on the edit form. I know that the theme function that builds the form element is 'theme_form_element', but if I alter that, it alters all the form elements. I'm not sure how to target just the elements in my module or if this is even the route to go down.

Can someone please point me in the right direction? I have been stuck on this for days.

UPDATE 01Nov14

It's been a few days since I posted this question, and I'm still very stuck. Here's another screenshot that may be able to clear up what I'd like to do. How do I add a class in the wrapper divs pointed out in this screenshot?


texts: How to link a title from one view to a page of another view

texts:
I created a content type x.

I added 4 contents.

My contents look like this.

I created a views page. (xxx.com/mypage),

I created a views block placed in sidebar. (displayed sidebar of xxx.com/mypage),

This is how the page looks like,

Each time I click a title in sidebar, I like the corresponding views page to be displayed. Currently, title takes me to orginal content. Thats not what I want.

Example: If I click Chapter1 Title1, I like to see chapter1 title1 body page, If I click Chapter2 Title1, I like to see chapter2 title1 body page.

I think I need to use contextual filter and I am not sure how I can do that to make it happen.

Please advise.


texts: Views - No results behavior with Exposed filter criteria

texts: I have a views setup with one title field, exposed filter criteria and No results behavior (Simple Text). Problem is No results behavior shows before user applied any filter criteria. I need No results behavior to show up only if filter criteria didn't find any content. Help please and thank you!


texts: Drupal Vertical Tabs - add another item dynamically

texts:
I have a form which is divided into vertical tabs. I want to dynamically add another tab using Ajax. I've managed to add fields via AJAX and add another  item as a vertical tab item, but when I am trying to click it,it does not work. I'm getting TypeError: tab is undefined.

Here is the code:

    $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add another section'),
    '#submit' => array('mymodule_add_more_add_one'),
    '#ajax' => array(
        'callback' => 'mymodule_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
        ),
    '#limit_validation_errors' => array(),
);

function mymodule_add_more_callback($form, $form_state) {
$commands = array();

$current_id = $form_state['num_names'] - 1;

$subject = drupal_render($form['names_fieldset'][$current_id]['subject']);
$html = '
' . $subject . '
';
$commands[] = ajax_command_append(".vertical-tabs-list", $html);
$commands[] = ajax_command_invoke('.vertical-tabs .vertical-tabs-panes fieldset', 'hide');

$id = 'node_cv_form_group_custom_' . $current_id;
$class= 'field-group-tab group-group-custom-' . $current_id . ' required-fields form-wrapper vertical-tabs-pane fieldgroup-effects-processed';
$body = drupal_render($form['names_fieldset'][$current_id]['body']);
$html = '<fieldset id="' . $id . '" class="' . $class . '">
' . $body . '
</fieldset>';

$commands[] = ajax_command_append(".vertical-tabs .vertical-tabs-panes", $html);

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

}

function mymodule_add_more_add_one($form, &$form_state) {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;}

EDIT

The Vertical Tabs are generated by field-group module.


texts: how to remove element from node__product__type.tpl.php commerce kickstart

texts:
In my website with commerce kickstart, I would like to remove div with its class name "field_label" in node__product__type.tpl.php. I have no idea of how to code to remove it. Any suggestion is greatly appreciate.

html

    tshirt size:

node__product__type.tpl.php

<article<?php print $attributes; ?>>
<?php print "testing product testing" ?>
<?php print $user_picture; ?>
<?php print render($title_prefix); ?>
<?php if (!$page && $title): ?>

     <h2<?php print $title_attributes; ?>><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?>

<?php endif; ?>
<?php print render($title_suffix); ?>
<?php if ($display_submitted): ?>
<?php print $date; ?> -- <?php print $name; ?>
  <?php endif; ?>

   <?php print render($content['product:field_images']); ?>

   <div<?php print $content_attributes; ?>>
     <?php
      // We hide the comments and links now so that we can render them later.
       hide($content['comments']);
       hide($content['links']);
       print render($content);
    ?>

    <?php if (!empty($content['links'])): ?>
    <?php print render($content['links']);?>
  <?php endif; ?>
    <?php
      print render($content['comments']);
    ?>


texts: How to dynamically change the title of a menu item

texts:
I have a "new comments" menu item in the user-menu that is generated by a view.
I would like to change the title of the menu to include the number of new comments.

I tried using hook_menu_alter without success. I cleared the cache and rebuilt the menu using the devel function.

function newcomments_menu_alter(&$items){
  $items['newcomments']['title'] = '5 New Comments';
}

When I add a menu item with hook_menu() I can dynamically change the title with a custom "title callback" function. But I can't figure out what the "page callback" is to display the view.


texts:
I am working with Drupal 7. In my site am using the SMTP Authentication Support module to send emails. After sending an email, I want to get the unique encrypted message ID string. Now I am getting the message ID as:

Example:

user_registrationpassword_register for registration
user_password_reset for reset password.

How can I get the unique encrypted string for each email sending from the site?


texts: Unable to submit form to database in custom module

texts:
I am building a custom module and I'm unable to get the form to talk to the database. The section for uploading to the file system works fine.

This is MyModuleBlock.php

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\my_module;

/**
 *  @Block(
 *    id = "my_module",
 *    admin_label = @Translation("Add Image"),
 *  )
 */

class ImageBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
      // stuff here;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['image'] = array(
      '#title' => t('My Module'),
      '#type' => 'managed_file',
      '#upload_location'=> 'public://images/',
      '#required' => FALSE,
    );

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */

  public function submitForm($form, FormStateInterface $form_state) {
      MyModuleDB::add();
  }
}

The MyModuleDB.php (I am trying out plain text to see if any errors or anything pops up):

<?php

namespace Drupal\my_module;

class MyModuleDB {
    static function add(){
        db_insert('my_table')
            ->fields(array('image' => 'img1'
            ))->execute();
    }
}

I'm at a total loss here. The tutorials I've found claim that this should work out fine, but it isn't working for me at all. I even tried inserting into the database directly from submitForm() in the main block class. I also tried to add redirects to the submitForm(). I'm thinking the issue is in that function, but I don't see what the issue could be.


texts: files missing in web/ folder when using composer.lock file

texts:
I have run into an unexpected problem with a fresh install of drupal 8.

Initial setup

$ git clone https://github.com/drupal-composer/drupal-project dp
$ cd dp
$ composer install

This works fine, installs everything. I now repeat the same thing, and use the composer.lock file from the above.

$ git clone https://github.com/drupal-composer/drupal-project dp2
$ cp dp/composer.lock dp2/
$ cd dp2
$ composer install

This time, however, the web/folder just has folders in it, no files. In fact, a diff between the two folders shows a number of missing files including in sites and sites/default.

I thought the composer.lock file was used to simply lock the versions of the modules down.

What am I missing here?


texts: Store information from hook_form_alter to be used in later hook_user_update?

texts:
I have a hook_form_user_profile_form_alter (hook_form_FORM_ID_alter) where I'm capturing user information that was changed when a user updates their profile.

I want some of that information available in hook_user_update, which is called after the form alter - maybe no more than 6 fields.

Is there a way to hold some of the information from the hook_form so it is available when I get to hook_user_update? I'm looking for a server side solution. In Java I could use class variables or session storage. I see PHP has session storage. Is that the best practice or is there's a Drupal specific solution or a better PHP usage pattern?

Since someone will probably ask why I don't perform what I need done in hook_form_user_profile_form_alter:
That function gets called twice (which can be problematic) and I cannot be sure that the transaction is complete until I get to hook_user_update. So I feel that hook_user_update is a much better place to execute what I need to execute, because I'm synchronizing information with another application. I need to be sure the transaction went through before I perform the call to the other app.


texts:
I have created some views to list specific content types. Is it possible to make the view page searchable?

To solve the issue, I have tried installing the Search API module, but nothing appears to solve the issue.


texts: Adding contacter's email to reply field in contact form email

texts:
In Drupal 7, when someone used our contact form, we would receive an email and could click "reply" in the email we received and have their email be in the "to" field. Since upgrading to Drupal 8, our own email shows up in the "to" field when replying to people who sent us an email through the contact box. Can anyone shed some light on how I can get the contacter's email to show up in the "to" field?

Can I set a "reply-to" field in the email to get this to work? I am using the core contact module, not webform but I am open to using the webform module if it can allow me to fix this.


texts: I allow my administators to add panels, articles, blog posts, forum topics, etc but it only shows the default set that regular users get which is blog posts and forum topics. Ive checked and all the people are set to admin. How do i fix this?


texts:
I create advanced search with views.
I want type one word and search it in 10 fields that I create in content and show all contents that use "word" in each fields


texts: Displaying fields in multiple rows for one node with Views format

texts:
In a view I need to display a node's fields in multiple rows, how can I achieve that?

The node contains:
Port1Name
Port1Arrival
Port1Departure
Port2
Port2Arrival
Port2Departure
Port3Name
Port3Arrival
Port3Departure

I need the display to be in a table as (for example)

Port Arrival Departure
Istanbul 1/1/11 2/1/11
Mersin 2/1/11 4/1/11
Mykanos 5/1/11 6/1/11

When I used table, it puts all fields on the same row, as it detects the view contains only one node.
I tried with grid..played with settings, no luck.
I tried Views Secondary Row and it only works when I need to have two rows, not more...

How can I achieve this with views formats?


texts: Twig template not rendering new field variable

texts:
I created a new field for a custom block type and have already exported necessary yml files and updated the yml for different view modes.
However, when I make a reference to the new field using the correct field_machine_name, it doesn't recognize it.
This new field is a checkbox, that when enabled, hides the h1 header of the page, but is still visible for screen readers.
sample code:
{% set hide_header_title = content.field_hide_header_title|render|striptags|trim %}

 {% if hide_header_title == 1 %}
    {% set hide_header_title = "show-for-sr" %}
  {% else %}
    {% set hide_header_title = "block" %}
  {% endif %}

With the code above, I'm only getting to the else statement.


texts: Get the current ProductVariation from the formElement of a custom widget in the "Add to cart" form

texts:
I've a custom field in my Order Item, i need the value of a field of my ProductVariation in the widget of my custom field.
Let's say that my Variation has a "remote ID" field, when i select one of the Variation in the Add to cart form, in my custom field i've to retrieve that ID and use it to do some things.
If i've only one Variation everything works great doing something like that:
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $purchased_entity = $items->getEntity()->getPurchasedEntity();

    $my_cusrom_id = $purchased_entity->get('my_variation_field')
      ->first()
      ->getValue()['value'];
  }

The only problem is that if I have multiple variations, when i chose one from the select, in this code always the first one is returned from the getPurchasedEntity method, and i see no informations in $form_state or $form of something that could be useful.
Is there a way to retrieve the selected variation from there? seems strange that's not possible...


texts: "Cannot declare self-referencing constant database.inc line 2101"

texts:
Suddenly, I got this error when I was configuring rules; the entire Drupal site is not accessible, not even update.php.

  Fatal error: Cannot declare self-referencing constant '' in I:\My Documents\web\xampp\htdocs\mysite\includes\database\database.inc on line 2101

The last thing I remember was configuring rules with custom PHP.


texts: How do I send an email notification to a user who flagged another user using rules?

texts:
I have the Flag module set up so that the users can flag each other; there is a link shown on the user profile page. I would like to have those users who flagged another user to receive a notification by email when the flagged user post new content.

How can a user who is 'following' another user to disable email notification on new content?

I am using Drupal 7.


texts:
I am attempting to use the Flickr module 7.x-1.x-dev to display a block of recent photos from a photostream on Flickr. I have setup the API keys and correct user ID, but the block is not producing any output. I've checked the Drupal logs and can't see any issues. I've also run cron and cleared the cache.

Does anyone know how to get this module working or of any alternatives to this module that work in 7? I tried Flickrippr but it produced a lot of PHP errors that brought the site down.


texts:
Using the email module, you only have the option of outputting the email address as a link, the email address as plain text, or a link to a web form. What I want is to just print the word "email" as mailto link.

For example: In display suite using the link field formatter, you can opt to use the label as the link so the website displays the word "website" which is a hyperlink to the actual url. Is their anyway to do this with email?


texts: I have a paragraph that I fully themed into a contact form with the necessary  tags etc... Now my question is: How do I add the actual functionality to this? Because right now it's just plain html in a template without any logic handling the form submit.


texts: Why doesn't the "auto-create feature" in the Ftools module work on Features 2.x?

texts:
I've been using the Ftools module for a long time to create features more easily; this module provides a "auto-create feature" link on the features configuration page.

However, when I upgraded from Features 1.x to Features 2.x., "auto-create feature" no longer works; it simply removes everything from the .info file.  What am I doing wrong?


texts: Why does my content type need to be reviewed before it can be saved?

texts: I created a new content type and when I want to create new content of this content type, on the bottom I only get the Preview button, the Save button does not show up and I can not find in the content type settigns how I disable this "must preview before save"-feature...


texts: how to get user name in a view instead of uid

texts:
I have a drupal 7 website that uses a view to show the content.  The Content UID shows as a field I can display, but I want to display the username instead.  It says "The user authoring the content. If you need more fields than the uid add the content: author relationship"  , which I don't understand .  Where do I add the content author relationship?
thank you,


texts: How to perform entity validation on code level?

texts:
I have an entity that has a field attached to it and the values that user types into the field has to be globally(website) unique(compared to other entities).

I have added validation to the entity form but what if I create this entity programmatically? How can I prevent the entity to be saved into the storage?

I've noticed there is a validate method in ContentEntityBase, though not in ConfigEntityBase.
Is this the place for it? If so, I could use some examples.


texts: Does Drupal.t() inside JS file has the same restrictions as the PHP t()?

texts:
I have read that the string parameter passed to t() function should be literal, which excludes:

variables, even the parameters of a function: t($description)
a concatenation of strings: t('If you want to add a link, click on' . 'this link.')
the value returned from a function:t(get_menu_description())
a constant: t(MYMODULE_MY_WIDGET_TITLE), t(MyClass::WIDGET_TITLE)

as mentioned here Is it always bad to pass a variable through t()?.

So, does Drupal.t() inside JS file has the same restrictions? as I have find a string inside some module that is passed as a variable

 $(this).addClass('open').text(Drupal.t(settings.linkText));

This string settings.linkText can't be located at the translation interface and I tried to change it to

 $(this).addClass('open').text(Drupal.t('@txt',{@txt:settings.linkText}));

but still couldn't find it. Any Ideas?


texts:
Select query will always return a result set object of one record.. There are several ways to then retrieve data from that result set, depending on the use case.

   user's flaged entity id:

  $query = db_select('flagging', 'f');
  $query->condition('f.uid', $data['uid'], '=');
  $query->fields('f', array('entity_id'));
  $result = $query->execute()->fetchObject();

and also used following query statements

         $query->__toString()

         SELECT f.entity_id AS entity_id  FROM {flagging} f WHERE  (f.uid = :db_condition_placeholder_0)

I replace the db_condition_placeholder_0  with specify uid.
It return me the right result (2 results).

   **$query->execute()->fetchAssoc()**`, return one result.


texts: Drupal: User personalization of Taxonomy terms

texts:
I have a requirement within Drupal to allow registered users to personalise the taxonomy terms that they see and use (leaving the defaults as they are) but haven't found any other information online on the best way to approach this - or if a module exists that does this. Specifically, the requirements are:

Drupal 6 or 7 (7 preferred)
Taxonomy items will be flat lists - not nested trees
The initial items will be the default set
Registered users can each change their default terms to suit their purposes - but the default set is untouched. Other users could have their own set. This would need to work similarly to internationalization (i18n).
Duplicate customizations are allowable.
Using (searching or displaying) duplicate customised terms will concatenate the result set of all the translated terms.

To try to give a simple example. Purely for illustration purposes, lets say the vocabulary is Soldiers.

The terms in the default set is:

Guard
Footman
Swordsman
Archer
Sergeant
Captain

and an orc user wants to reference the same terms with these customisations:

Peon     (Guard)
Grunt    (Footman)
Grunt    (Swordsman)
         (Archer)
         (Sergeant)
Chief    (Captain)

So when using the system the orc user has the following soldier list:

Peon
Grunt
Archer
Sergeant
Chief

Where 'Grunt' references both the Footman and Swordsman terms from the original. Archer and Sergeant use the defaults.

Hope this makes sense.


texts:
I have to display some data from a CRM system. I need it like following.

Let suppose I have a content type "Cars" which have following fields

Car ID,
Car Name,
Car Model,
Car Price

I am creating a node from Cars content type and want the above fields to grab data from CRM. So if Car ID is 1 then Car Name, Car Model and Price will be fetched from the CRM system.

I want to know if the data from the CRM could be available as JSON, how can we map that with these fields?


texts:
I have constructed a form manually using the Form API. I have one field in particular that needs to have it's markup changed a tad.

The #prefix/#suffix output should come immediately before/after the input control. I think the output currently looks like:

Can I override the themeing for a single field using something like:

$form['control'] = array(
  '#theme' => 'control_field',
  '#title' => 'Some title',
  '#type' => 'textfield'
);

Do I then implement MYTHEME_custom_theme in the templates.php???

Do you know of any exmaples I might use?

I tried adding:

function theme_control_field($variables) {

}

This did not seem to work...also I need control over all the markup for this field not just the field control but I need to relocate the prefix/suffix output as well!?!

Regards,
Alex


texts: How to Alter Webforms Upload Ajax Callback?

texts:
When I hit the Upload button to load files, ajax is being triggered and alter my URL thus overwriting my $tid.

Hello I want to alter the webform actions after an ajax request so that I pass my $tid to that ajax callback like this:

$form_state['triggering_element']['#name'] = $tid;

I cannot find the upload webform ajax callback and how to alter it.

Thanks


texts: Takes too long to render a product display with 6000+ variations

texts:
I have a product with several attributes and each one with several options. The total variations is over 6000.
The problem is that rendering takes too long. I've enable Devel module and here are the results:

Executed 72 queries in 323.6 ms.
Page execution time was 13870.81 ms.
Memory used at: devel_boot()=1.44 MB, devel_shutdown()=62.56 MB, PHP peak=69.5 MB.

So I guess there's some bottleneck at the code.

Some notes about the implementation:

I need a unique price for each variation.
I'm using vanilla Drupal Commerce.

There's any way I could improve performance?


texts: How do you include a user's default image in a Drupal 7 view that lists people?

texts:
I have a view in Drupal 7 that lists people (users). It shows the username and the standard user picture field. If a user has a set image, it comes through perfectly. However, for users that didn't set a profile image no image is shown, even though I have a default profile image set in the people settings for the site.

How do I get views to use the default profile picture for people that do not have a profile image set?

Update: I wasn't clear. I know how to use the default image in the no results behavior. The issue is that I can't get the default image to use the imagestyle I use for the other images.


texts: PHPUnit test complex method that use drupal service within it

texts:
I have a method of a class that returns me the list of fields that have been created outside of core Drupal. The method is:

/**
   * @param $contentType
   * @return array $fields
   */
  public function getContentTypeFields($contentType) {
    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entityManager */
    $entityManager = \Drupal::service('entity_field.manager');
    $fields = array();

    if (!empty($contentType)) {
      $fields = array_filter(
        $entityManager->getFieldDefinitions('node', $contentType),
        function ($fieldDefinition) {
          return $fieldDefinition instanceof FieldConfigInterface;
        }
      );
    }

    return $fields;
  }

So you pass in a content_type name and the method will return an array of fields that have been created by us, so not the default Drupal fields.

I cant figure out how to write a Unit Test for this method, can someone please help?


texts: Drush 8x working from directories above web root, but not in web root

texts:
I need some help trouble shooting Drush. I'm on a shared server, Hostgator, running Linux and PHP 5.6.3.

My install looks something like home/public_html/websites/MyDrupal

I have installed Composer globally as well as Drush
.bashrc includes:

# .bashrc
export PATH=$PATH:~/.composer/vendor/drush/drush
[ -z "$PS1" ] && return

# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi

# User specific aliases and functions
alias composer="/usr/bin/php-cli ~/bin/composer.phar"
alias drush="~/.composer/vendor/drush/drush/drush"

Composer runs from any directory within my host space.

Drush will run, using the directory hierarchy example above, from 'home', 'public_html' and 'websites' but if I run drush status within 'MyDrupal' I get an error:

Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected 'finally' (T_STRING), expecting catch
(T_CATCH) in
/.../public_html/bhsu/vendor/symfony/dependency-injection/ContainerBuilder.php,
line 452

Parse error: syntax error, unexpected 'finally' (T_STRING), expecting catch (T_CATCH) in /.../public_html/bhsu/vendor/symfony/dependency-injection/ContainerBuilder.php on line 452

Would appreciate pointers... thanks


texts: Why would the page at admin/people/permissions have very little information and appear like it doesn't have any CSS style applied?


texts: How to show upcoming events in the current month with calendar module?

texts:
I'm using Drupal 7 Module Calendar, Views and Panels.

I used the block-mini-calendar view of Calendar module to display on my frontpage.

Then I created a custom view to display only a list of the day's events selected by the user.

I put as Context-Filter:
Date: Date (node) (Content: Dates - start date (event_calendar_date))

And Filter Criteria:
Content: Published (Yes)
Content: Type (= Event Calendar)

Then, I created a panel-page that receive the arguments of the date by URL and passes to my view created (My view created above I've put in my panel created with the URL of events/%date).

All previous flow works well. I'm listing all events of the day selected by the user. But, I need to display all events that are within the range of parameter passed in the URL(day selected) and the last day of the current month that the user is.

What changes should I do in my view?

Sorry for my english. Thanks in advance.


texts: PhotoSwipe display only one image from Views grid form

texts:
I created a grid view to display several node images thumbnails (3 columns, and multiple lines), and following PhotoSwipe usage found whithin the README.txt, I specified the CSS class "photoswipe-gallery" to display the field image.

Now when I click on one image from the view, I got the full sized Image as I wanted, but I can't move to the next or previous image that exist within my view grid.

Is there anybody knowing how to do it?

Thanks in advance


texts:
I have a series of sites that use the same theme.  What I'm looking to achieve is to manage the main menu (or a standard menu) via a module instead.

Reasoning:
Most of these sites will have the menu the exact same.  If I need to change something, I would do it in the module. I could put it in the theme, but I'd rather the site admins not have control over appearance or to change the theme, have the ability to add to the menu if that have a small item that needs to be placed there, or the ability to simply not show the entire menu and manage their own.

I've tried the following, but every time the cache is cleared, a new item is added. If I change something, it just adds a new item and leaves the old one.

function something_mainmenu_menu() {

    $items['external'] = array(
        'title' => 'External Item',
        'link_path' => 'http://www.whatever.com',
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu'
    );
}

Is this possible in Drupal as a module, or should I just put it in the theme and do a case based on the URL?


texts: Enable/Disable field values based on another field's value

texts:
I am using Drupal 7 with the Entityform and Conditional Fields modules to build a form and need to see if it is possible to disable a value in one field based on the selected value of another field. Here are the details:

Field: Source Region
List (Text) - Radio Buttons

Values:
US-East
US-West
APJ
EMEA

Field: Destination Region
List (Text) - Radio Buttons

Values:
US-East
US-West
APJ
EMEA

The behavior I am looking for is this:
When a region value in Source Region is selected, I need the corresponding value in Destination Region to be disabled but the rest of the values to be selectable. This is to make sure the Source and Destination regions are not set to the same value.

Example: Source Region selected value is US-East, I need Destination Region US-East gets disabled.

If this is not possible with the Entityform and Conditional Fields modules, please let me know how best to obtain this functionality. If this means writing a form from scratch, I am willing to do this but need some type of tutorial or howto document to learn how to do this.


texts:
I'm building pretty simple forms loaded with AJAX and displayed with Foundation Reveal. I can get the form submission to work with AJAX, and update the markup inside the reveal, but with the AJAX-powered submission button, the validation method is not executed.

Why? How can I get the form validated with AJAX?

I just want the normal form validation process, where I can add my own validation to ::validateForm and then pass control to my AJAX form submission handler.

$form['submit'] = [
  '#type' => 'submit',
  '#value' => 'Tallenna',
  '#ajax' => [
    'callback' => '::ajaxFormSubmitHandler'
  ]
];

I tried with $form['#validate'] = array('::validateForm');, but it doesn't work. I also tried calling Form::validateForm($form, $form_state) in the submission handler with the following code.

Form::validateForm($form, $form_state);
if ($form_state->hasAnyErrors()) {
  $form_state->setRebuild();
  $errors = $form_state->getErrors();
  return($form);
}
else {
  $form_state->setRebuild(FALSE);
}

I can set up the callback for a single element.

$form['field_asiakkaan_nimi'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Asiakkaan nimi'),
  '#required' => TRUE,
  '#ajax' => [
    'callback' => array($this, 'validateNimiAjax'),
    'event' => 'change',
  ],
  '#suffix' => ''
];

I can use that callback for the field processing.

  public function validateNimiAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $message = 'Nimi validoitu!';
    $response->addCommand(new HtmlCommand('.nimi-valid-message', $message));
    return $response;
  }

This doesn't seem to be the proper way to go about this.

I am also getting this error:

  The form has become outdated. Copy any unsaved work in the form below
  and then reload this page.

How can I get AJAX delivered forms validated and processed?


texts: Drupal 7, superfish menu hidden in garland theme

texts:
I am using the default theme garland in Drupal 7.23 with a superfish menu put on the first sidebar block . (the side on the left).

But when I try to open the menu, and on my content block I have a view or a nivo slideshow block the menu is hidden. Where should I put the z-index? (tried on the theme and on the menu but nothing worked)

Thank you


texts: How to fix call to undefined function libraries_get_path() in multi-site install?

texts:
I am setting up a multi-site Drupal 7 install. I have the base site set up correctly and running just fine. When I create the second site (a sub domain of the first site), the install.php script ran fine but when I try to view the site I get the following error:

Fatal error: Call to undefined function libraries_get_path() in /var/www/drupalhome/d7/sites/all/themes/mytheme/template-preprocess.php on line 75

I assume that since the second site inherits everything from the first site (since it is the default install) that the second site should display just fine. However it looks like the second site doesn't know about the libraries module and is throwing the above error (at least that is my interpretation of it). My question is: how can I fix this?

Thanks.