texts: views - how to filter by birthdays dependent on the current date

texts:
I have the following use-case:

I have a custom content type called profile which has a birthday field (of type Unix timestamp).

I need to be able to filter all profiles that have a birthday in the interval (-3 days from now to +7 days from now). How can I achieve this using views? Do I need to make a custom filter or custom contextual filter or some other custom plugin?

Thanks a lot for your input.

Update:

So I started building a custom filter with the following:

my_module/my_module.module

<?php

/**
 * Implements hook_views_data_alter().
 */
function my_module_views_data_alter(array &$data) {
  $data['node__profile_birthday']['birthday'] = [
    'title' => t('Filter by birthday'),
    'group' => t('Content'),
    'help'  => t('Filter profiles by birthday.'),
    'filter' => [
      'id'    => 'birthday',
      'field' => 'profile_birthday_value'
    ],
  ];
}

my_module/src/Plugin/views/filter/Birthday.php

<?php

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\NumericFilter;

/**
 * Basic filter handler for Birthdays.
 *
 * @ViewsFilter("birthday")
 */
class Birthday extends NumericFilter {
  /**
   * Override the original Views opBetween behavior.
   */
  protected function opBetween($field) {
    // The birthdate is between -3 days and +7 days from the current date
    $expression = "DAYOFYEAR($field) BETWEEN ((DAYOFYEAR(CURRENT_DATE())) - 3) AND ((DAYOFYEAR(CURRENT_DATE())) + 7)";

    $this->query->addWhereExpression($this->options['group'], $expression);

  }

}

I am still having issues with views not properly saving the values of min and max of the between operator. Any help is appreciated.


texts: How to use $form['#action'] in Views PHP field

texts:
I print the comment form for each node in my view with the Views PHP module. The URL of the view is user/%/selection, and the code I am using is the following one.

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_node_MYCONTENTTYPE_form', $comment);
$form['#action'] = url('user/'.$row->uid.'/selection');
print render($form);

When the form is submitted, I get /node/nid#comment-17 as URL.

Could you explain why $form['#action'] doesn't work?


texts: How to add to index unpublished content by apachesolr?

texts:
I use apachesolr module for index content.
As I understand, this module does not provide indexing unpublished content.
Is it some trick to avoid that?

I try to use this hook and change status callback, but it does not work.

function hook_apachesolr_entity_info_alter(&$entity_info) {
  // Validate each entity if it can be indexed or not. Multiple callbacks are
  // allowed. If one of them returns false it won't be indexed
  $entity_info['node']['status callback'][] = 'apachesolr_index_node_status_callback';
}

p.s. it duplicate with this issue, but there no activity and it's very old.


texts:
I have a very big content written as a Basic Page where i want to construct a block with a menu tree structure next to it, in order to let users to click on a link and to guide them to the appropriate section of this huge article. Imagine that there will be some  tags with a specific "id" next to a section of the content for example. How can i implement this and what approaches should i follow?

Thanks in advance.


texts:
I am trying to learn Drupal, and getting stuck every hour. I wish someone could walk me through this. I am trying to create a Employee-Company relationship. I have created a Company Content Type with just Name, Address and Telephone Numbers. And a Employee with Name and an Entity Reference to Company and multi-value Term Reference to skill set.

Now in my page skill/[whatever_the_skill_may_be] - I get a list of Employee. This happens automatically. Now I want to show the Company information along with each employee, but surprisingly can't seem to do this easily. I get the Company name which can be linked, but not the address or Telephone number.

Some of the pages I searched for the answer seem to suggest creating a View for this. I am not sure if I really need to, for such a simple requirement. But even if I do so, how do I override the default view of skill/[whatever_the_skill_may_be], and also the employee/[name-of-employee] page, where I would like to show the company information?

I hope I am not asking a stupid or very obvious question. Thanking u in advance,


texts:
I've an problem displaying my sidebar...

I've build a custom block which has these settings:

And for display options, I've choose these:

But for some reason, the block doesn't appear in my sidebar on the page jobs/BusinessAnalyst. So what do I have to do to get this block into place?

Here is my custom .tpl file:

// Unset all the things we don't need
unset ($content['language']);
unset ($content['downloadable_documents']);
unset ($content['field_job_category']);
unset ($content['field_job_sub_category']);

// Finally, print the content (the ShareThis module)
print render($content);

I've checked, and the $page['sidebar_left'] is empty.


texts:
I create a form and a page with controller in Drupal 8.

I want print value of my example input after submit form.

For example my input name is "Tel_number".

My code in controller page is:

<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
class MymoduleController extends ControllerBase {
    public function mymodule() {
      $form['test'] = array (
         '#markup' => \Drupal::request()->request->get('Tel_number'),
      );
    return $form;
    }
}
?>

But no resault print.


texts: Set data (current nid) to entity reference field with rules and VBO

texts:
I'm currently stuck in the creation of a custom rule.

I would like to show a button on some content type, this button called a list of other content called "guide". I list these contents (guide) in a view and I added a field to associate a rule vbo.
In the type of content I have a guide entity reference fields might add my id of the current node content (the button add to the guide) to guide one or more listed.

How to perform the action:

get the nid of current content
define the fields at the end of the reference entity or selected guides
save the guide(s)

Note : The list of guides is showed in a lightbox when button "add to guide" in a content was clicked.

Thank you very much in advance


texts: Make Conditional Field work with Price widget

texts: I would like to know if there's a way to make the Conditional field module here work with the Price widget. For example, I want to allow the user to input a price when he checks something with a checkbox.


texts:
Using webform I have created a questionnaire and now I need to be able to print the results on paper. My first solution was going to the result page print out from the browser. Unfortunately, this does not look good on a print when print out.

Here is how it looks like browser.

And I think this looks very decent and acceptable, but when I print this out it will looks like this.

 The print out cut most of my webform results and without all my results this is useless for me.

My second solution was to try it out the Webform2PDF module. However, every time I try to used it does not work for me.

I have try to print out the e-mail I get from webforms but the results are on plain text and the results from the e-mail does not looks very professional. These results are have to be very presentable on paper.

So my question is what is the good approach of printing out the webform results.


texts: Use a database specific function in dbtng (e.g. uuid in db_insert)

texts:
I have a table that contains a char(36) field for a uuid. It seems like I can insert data into that field with a mysql query like: INSERT INTO mytable (uid, event_guid) VALUES (1, uuid());. I'd like to make a query like that in DBTNG syntax, but I believe I will just insert the string "uuid()" into the column.

db_insert('mytable')
  ->fields(array('uid' => $uid, 'event_guid' => 'uuid()'))
  ->execute();

So...do I just use db_query? Is there some magic in dbtng to handle this?


texts: Unable to render posted date in node--article.tpl.php

texts:
I'm attempting to render the posted date of an article in a specific way. I understand that there is a

Display author and date information.

Checkbox in the content type editor. However I don't believe that would resolve my issue. I'm using the domain access module and the articles on the domains using a different theme cannot be altered. Certainly not how they're displayed anyway.

Is there a way to programmatically grab the posted date from within the template? Is there something similar to

print render($content['body']);

That I can use to render that information? Or is there a function I can call that contains that information?


texts: What's the best practice to show a node's fields in different regions?

texts:
In D7 we used to create a view for nodes, with each field having an own display. Each display creates a block to place in any region of the site. But of course, Views are SQL-heavy.

Now, Drupal 8 is all fancy. What's the Drupal 8 way of showing a node's fields in different regions of the page?

Edit: my current attempt is to create a custom module which provides a block for each specified field.


texts: Drupal Views Exposed filter ( Taxonomy )

texts:
I have 3 fields ( Exposed filter ) 1 Country 2 State 3 City

When a respective Country is selected in the 1st field, I want the second filter ( Dropdown or autocompete ) to display states of the country selected in the 1st field & when this is done based on the state selection , I want the 3rd field to show only the cities belonging to the state selected in the second field.

How can this be done ? any help ?


texts:
I have created a webform which when submitted will create a new user for my Drupal 8 site.

The user must enter his username, email, and some additional data.

I am using below code to create & validate a user:

namespace Drupal\my_module\Plugin\WebformHandler;

use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;

use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
// use Drupal\taxonomy\Entity\Term;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create New User Account when a webform submission is submitted.
 *
 * @WebformHandler(
 *   id = "Create New User Account",
 *   label = @Translation("Create New User Account"),
 *   category = @Translation("Entity Create"),
 *   description = @Translation("Create New User Account when a webform submission is submitted."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class CreateNewAccountHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

// Function to be fired while submitting the Webform.
public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

// Build Drupal DateTime & set correct format for your query.
  $current_time = \Drupal::time()->getCurrentTime();

// Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Get 'Username' Value.
    $username = $values['username'];

    // Get 'Password' Value.
    $password = $values['password'];

    // Get 'Full Name' Value.
    $FullName = $values['full_name'];

    // Get 'Phone Number' Value.
    $PhoneNumber = $values['phone_number'];

    // Get 'Email' Value.
    $email = $values['email'];

// Create user object.
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $new_user = \Drupal\user\Entity\User::create();

    //Mandatory fields.
    $new_user->setPassword($password);
    $new_user->setEmail($email);
    $new_user->setUsername($username);    // Alphanumeric (abc, 123), space ( ), period (.), hyphen (-), apostrophe ('), underscore ( _ ), and the @ sign are only allowed.
    $new_user->set("langcode", $language);
    $new_user->set("preferred_langcode", $language);
    $new_user->set("preferred_admin_langcode", $language);
    $new_user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object.

    //Optional Fields
    $new_user->set("init", 'email');

    // Custom Fields
    $new_user->set("field_full_name", $FullName);
    $new_user->set("field_ph_nbr", $PhoneNumber);

    // Validate the user for possible errors.
    $violations = $new_user->validate();
    if (count($violations) > 0) {
      $property = $violations[0]->getPropertyPath();
      $msg      = $violations[0]->getMessage();

    // Show a custom message to user.
        \Drupal::messenger()->addError(t("$msg"));

      return FALSE;
    }

    // Activate the user Object (Status = Active).
    $new_user->activate();

    //Save user
    $new_user->save();

    // Get the new user ID.
    $new_user_id = $new_user->id();

    // Log in the user.
    user_login_finalize($new_user);

However, every time I try to create a new user using the webform, I got the below error:

This value is not a valid email address.

I have tried with:

someone@hotmail.com
someone@outlook.com
someone@gmail.com

What is wrong with my code ?


texts: Product variations are causing duplicates to show up in filter results

texts:
I'm using Drupal Commerce and have created a different product for every variant combination of color and size. For example, if I'm selling a skirt with multiple colors and sizes I'd have a product for "color:blue size:small", "color:blue size:medium", "color:red size:small", "color:red, size:Large", etc.

I created a view for my products and have added exposed filters for color and size to this view. The problem I'm having is that I'm getting duplicates because of the sizes. I don't mind if the filter results show the same skirt twice in different colors, but I don't want results showing duplicates for different sizes. i.e: "color:blue size:small", "color:blue size:medium".

I've tried adding the filter "Content: Product:delta (= 0)", which eliminates size based duplicates. The problem with this is that it also gets rid of color based duplicates, which cause my color filter to stop displaying different colors for the same skirt. For example, if Content: Product:delta (= 0) is added and I set my color filter to red skirts nothing will show in the results.

Is there a way to add a delta (= 0) filter to only the "size" attribute? I'm guessing this would fix my problem if it's possible to do.

This issue has been killing me and I really need it resolved. Any help would be greatly appreciated.


texts:
I want to get the meta description of a page and pass it on as a parameter to another function. Something similar to get_post_meta() in WordPress where you can get the meta values after you pass the page id or the node id.
I've searched and all I could find is a function to add meta ( drupal_add_html_head ) but nothing to get meta data. Thanks in advance for your time.


texts:
I have the Boost and Domain Access modules working correctly. But I've found that if the cache is flushed for one domain it doesn't clear for the others. So if content is added to one, it won't show for others until cron has been run.

Any way to fix this at all?


texts:
When the user creates a blog entry, I want the user to be able to make some selection from a listbox. Therefore I want it to be a function where I drag and drop between one prefilled listbox (where the content will stay even when dragged) and an empty one. Pretty much like this example: http://jqueryui.com/sortable/#connect-lists

How am I able to achieve this? Is there any module out there that can help me reach this goal?


texts:
In Drupal 8 I am trying to insert some data in my custom table. While executing query I am getting error:

  InvalidArgumentException: Placeholders must have a trailing [] if they are to be expanded with an array of values. in Drupal\Core\Database\Connection->expandArguments()

Please find my code below:

$qt = new \stdClass();
$qt->name = 'test name';
$qt->machine_name = 'test machine name';
$qt->settings = array('setting1'=>value1, 'setting2'=>value2);

$query = \Drupal::database()->insert('my_custom_table');
$query->fields([
  'machine_name',
  'name',
  'settings',
]);
$query->values([
  $ob->machine_name,
  $ob->name,
  $ob->settings,
]);
$query->execute();

If I am giving values like below it is working. Please help me whats wrong with above code.

$query->values([
  'test',
  'ttt',
  'dfs',
]);
$query->execute();


texts: Tips to move existing angular + cordova to drupal gap?

texts:
I have created a mobile app using cordova and angular framework which is in production already. Now I am planning to switch to DrupalGap with my existing angular application.

I think support for angular in DrupalGap is only available in DrupalGap 2.x which is not useful for production use.

So to use DrupalGap 1.x in my existing app, do I have to remove the angular related code (like controllers,routes etc) and replace with DrupalGap menu and its callback?

Is there any other way to re-use the existing angular code in DrupalGap1.x?


texts: Loop an Entity Reference Vocabulary Field

texts:
So working through my rule I would like to use a loop to execute an action.

In my content type I have an entity reference to a vocabulary called "Contacts".

I want the loop to loop through all the entity's in that field; however, in the loop LIST date selector it will not let me select just the field, it keeps wanting to drill down further to vocabulary, parent ect..

field-contact is the entity reference to the vacabulary

.

It seems to work if the list is just a regular field list on the content type itself but not when it's an entity reference to a taxonomy vocabulary.

Any tips/suggestions?

Thanks!


texts:
I've created a view block with views3.
When I attach the views block to a node, I want to know if the node is sticky and if the content type is "lodging".
If the criteria are met, do not display view result.

In the views filter (php field) I've created the following code.

if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid); // get node id
}
$sticky_status = $node->sticky;  //  get sticky status
$node_type = $node->type;  // get node type
if ($sticky_status == '1' && $node_type == 'lodging') // condition if sticky is 1 (active) and node type is "lodging"
{
  $view->result = null;  // do not display views
}

The code is working fine and I get the desired result, however I also get the following warning message:

Warning: Invalid argument supplied for foreach() in views_php_handler_filter->php_post_execute() (line 84 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_handler_filter.inc).
Warning: array_slice() expects parameter 1 to be array, null given in views_php_plugin_pager->post_execute() (line 46 of /var/www/html/planetlodge/sites/all/modules/views_php/plugins/views/views_php_plugin_pager.inc).
Warning: array_values() expects parameter 1 to be array, null given in view->execute() (line 1155 of /var/www/html/planetlodge/sites/all/modules/views/includes/view.inc).

Where is the error in the code ?


texts: How to run commerce_order_save() without triggering any rules?

texts:
I need to run commerce_order_save() on several Orders in loop but without triggering any Rules.

Is that possible ?


texts: add a new field in a view that uses a teaser view mode fomat

texts:
I have a view that extarct a specific content type, this view shows the teaser view mode for rendering fields and not fields format :

the teaser view mode is managed with display suite module to order content type's fields in custom regions.

Im using hook_node_view to add a new field conditionally :

function MYMODULE_node_view($node, $view_mode, $langcode){
    global $user;
    $uuid = $user->uid;
    switch ($node->type){
        case "rewards" :

            if(!empty($node->field_reward_users) && isset($node->field_reward_users[LANGUAGE_NONE][0]['target_id'])){
                if($uuid == $node->field_reward_users[LANGUAGE_NONE][0]['target_id']){
                    $node->content['get_reward_link'] = array(
                        '#type' => 'markup',
                        '#markup' => l('Click Here', '/', array('attributes'=>array('class'=>'my-link-class'))),
                        '#weight' => 100,

                    );
                }
            }
           // dpm($node);
            break;
    }
}

when i debug i can see the new field in the $node object, but it's not rendered.
Have you any idea how to add fields conditionally in my case?

Update

I added a new preprocess field ("pre_rewards") via display suite, like montionned in the answer of Reynold, then I added the following prerocess function :

function MYMODULE_preprocess_node(&$vars){

    if(isset($vars['preprocess_fields'])){
        foreach ($vars['preprocess_fields'] as $key => $pre){
            if($pre == 'pre_rewards' && isset($vars['content']['get_reward_link'])){
                $reward_link = drupal_render($vars['content']['get_reward_link']);
                $vars['preprocess_fields'][$key] = $reward_link;

            }
        }
    }
    dpm($vars);
}

and the same thing the element won't be rendered! and it exists in the $vars variable when i debug!

also the new field created exists in manage field page of my content type :

So why it's always not rendering the content of this field in my page!?

Thanks in advance.


texts:
I have multiple sources which roughly looks like:

Wines - Contents: "1,2,3,4"
Sodas - Contents: "1,2,3,4,5"

I'd like to combine those into one taxonomy vocabulary, get them to be auto-created and referenced in the destination field. So I'd like to do something like the following. But, if I read the static_map documentation correctly, mapping multiple sources like this is not the way it works. Also, I'm not yet exploding the string in the example, which I think is mandatory to be able to map the values.

  field_drinks:
    -
      plugin: static_map
      source:
        - wines
        - sodas
      map:
        wines:
          '1': 'Sauvignon Blanc'
          '2': 'Chiraz'
          '3': 'Pinot Noir'
          '4': 'Malbec'
        sodas:
          '1': 'Coca-Cola'
          '2': 'Spa'
          '3': 'Sprite'
          '4': 'Tonic'
          '5': 'Bitter lemon'
    -
      plugin: skip_on_empty
      method: process
    -
      plugin: entity_generate
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: drinks
      value_key: name

How do I convert this to suit my needs?


texts: I'm currently using the Honeypot module for blocking spam and it does a great job at blocking bots but too many human spammers manage to get through. I tried Mollom but that blocks out too much ham which is definitely bad for me. What can I use in addition to honeypot to block human spam?


texts: How to create checkbox instead of radio for just 1 allowed value?

texts:
Because of this major Drupal 7 bug (http://drupal.org/node/811542), I cannot use radio options in my form.

I have three options in my form and I want them to be checkboxes, but the user can only select one checkbox.  By Drupal 7's auto form design, it converts single value items to become radios.  How can I get the below to become checkboxes that users can only select one without having to write my own module to override the form?

beef|I prefer beef

chicken|I prefer chicken

veggie|I am a vegetarian


texts: Get taxonomy term field from where is attached

texts:
I have a taxonomy vocabulary like this:

A
|--B(branch_field)
   |-- C(branch_field)

X
|--Y(branch_field)
   |-- Z(branch_field)

Each user has a reference to a taxonomy term.
I need to create a view where I pass taxonomy term attached to user for filtering data, but I need also to use the taxonomy term field "branch" in the view but I don't manage it.

This is what I see using Devel about user fields:

[field_category_user] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 39
                            )

                    )

            )

Can I expose term field and target id?


texts: I am currently developing my website. It is in initial stage. I got pretty good hand on Drupal7. But as Drupal8 is going to release in few days should I shift to drupal8 from now itself as my development is in very initial stage Or should I stick to Drupal7?


texts: Why only first of two jquery files loaded is running?

texts:
In my theme Basic, I'm loading 2 jquery files. Both two are loaded at front page, but only first loaded run. If I change loading order, again only first file do anything.
Here are the examples:

1)
Drupal.behaviors.basic = {
...some jquery stuff...

2)
Drupal.behaviors.basic = {
...some other jquery stuff...


texts: very simple form in block rendering incorrect values

texts:
I have a very simple code in block :

if ($vocabulary = taxonomy_vocabulary_machine_name_load('caller_details')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $output = drupal_render(drupal_get_form('taxonomy_form_term', $vocabulary));
}
echo $output;

the problem is that it sets the value of "name" in my form to taxonomy vocabulary name by default. Why is that?

Thanks for any suggestions!


texts: How to set Navbar to be a sidebar by default?

texts:
Drupal 7's Navbar module is:

In wide windows, a bar across the top, with no dropdowns, just links to main sections like Content, Structure etc
In medium-width and narrow windows, a sidebar or dropdown menu, with accordion-style dropdowns allowing primary menu items to be expanded and secondary menu items shown without leaving the page.

I want to give users the sidebar view, even on wide screen devices, so they can use the secondary menu dropdowns it offers.

I want it to look like this when the menu is chosen, even in wide devices, similar to the old Admin module:

I can't find any way to do this within Navbar. What's the simplest way to do this, with minimal hacking to the Navbar module or hard-coded overrides?


texts: Field Formatter Class and limit number of characters

texts:
I have to insert in a field (admin/structure/types/manage/article/display) a string of classes to get a button from a text but the "Field Formatter Class" field has a character limit so I can't enter the code which I need to get the result.
I did some research but couldn't find the solution.

My Class:
btn btn-sm btn-primary stpe-outlinebutton test-util-color-primary test-util-border-primary test-util-hover-background-primary test-util-hover-color-white test-util-hover-border-primary

Any help?

Best Regards


texts: How can I prevent certain roles from editing other roles?

texts:
I have user roles User Role 1, 2, and 3. I want a simple module that will make User Role 1 only be able to edit and administer users in User Role 2, and not User Role 3. Does anybody know of any module or other easy method to do that? It seems like there must have been somebody else who did something about their moderators being able to delete their admin accounts?

Please note that I'm not asking for anything about restricting the permission changing ability of roles.


texts: Recently i did small project for a community now their requirement is to include a block that contain a YouTube video frame and they have to display their YouTube channel there, So i have installed emfield module but i don't know how to implement that. Is there any suggestion like which module is comfort for these purpose ? and How to use emfield ?


texts:
I've created a content type with some custom fields, one of which is an image. When I try to render a node that contains some images uploaded like this the route is messed up, like this:

http://localhost/gisele-drupal//var/www/gisele-drupal/sites/default/files/contract.png

What can I do to configure this right?


texts: How to display a views slideshow placeholder?

texts:
I have a site where the user can add images to the content types page and (custom) project. These images are displayed in a views slideshow based on contextual filter on each page/project in a block. The slideshows are header slideshows, so there must be a placeholder slideshow, if no images are added. How can i accomplish this ? I need a solution where no further maintenance by the user is needed.

Do i have to put some if/else in the page.tpl.php or is there some more elegant way ?


texts: Theme files being pulled from sites/default/files rather than sites//files

texts:
I'm pulling down a repository of a D8 multisite install and running it locally.

The sites are set web/sites/default and web/sites/mysite.  In the root of sites there is a sites.php which contains

$sites['mydomain.com'] = 'mysite';

In the web/sites/mysite directory there is a settings.php which has

$settings['file_public_path'] = 'sites/mysite/files';

however when I visit the local site in my browser I can see that files are being served from e.g. /sites/default/files/2019-01/header-mysite.png (I've added the files directory in both sites/default and sites/mysite).

The odd thing is that when I visit the site that is actually available on the web (which I am told is running from the same repo / branch as I have locally, the files are being loaded from e.g. /sites/mysite/files/2019-01/header-mysite.png

Can anyone advise how I should try to address this?  I tried adding my local url to sites.php but it didn't seem to change anything.


texts: By default, Shipping information fields should be shown

texts: In Drupal commerce kickstart Checkout page, by default Shipping information fields should show and the checkbox should uncheck. I tried JavaScript, but it is not working. How do I do this?


texts:
I have created a view page with exposed filter and its randomly shows me some error like that:

Fatal error:  Call to undefined function i18n_menu_block_view_views_activites_activities_filter_alter() in  /includes/module.inc on line 1101

Fatal error: Call to undefined function i18n_select_block_list_a() in /includes/module.inc on line 1101

Fatal error:  Unsupported operand types in /includes/database/query.inc

but when i refresh the page it disappear !!!
the problem that this error happens randomly and does not give logical reason.


texts:
Someone updated modules in my Drupal install 5 days ago, and I would like to find out who.

I looked in Reports > Recent log messages, but this is filled up with so many php warnings that it only goes back 1 day.

I also tried searching for "update" in the watchdog table, but couldn't find any entries for the date I was interested in.


texts: Form alteration is not working from within my form class

texts:
I am following https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api for my hello world module.

Below is my code

namespace Drupal\hello_world\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements an hello_world form.
 */
class HelloWorldForm extends FormBase {

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

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

        $form['phone_number'] = array(
            '#type' => 'tel',
            '#title' => $this->t('Your phone number'),
        );
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Save'),
            '#button_type' => 'primary',
        );
        return $form;
    }

    function hello_world_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
        if ($form_id == 'hello_world_form') {
            $form['phone_number']['#description'] = t('Start with + and your country code.');
        }
    }

}

I also cleated cache. Not sure why form is not altering.


texts: Invoice module to run with commerce module?

texts:
I'm looking for the right module to include invoicing capabilities with the Commerce module, but none of them fully fit my needs. Are there any other modules to help with invoicing?

Commerce Invoice
Commerce PDF Invoice
Commerce Invoice Receipt


texts: Exposed date filter "date selection form element" and "granularity" settings are missing

texts:
I would like to create a block view from a content type which has an exposed date field. This has to be a dropdown field where only the years are listed.
There is no setting possibility of the exposed date field where I could define these properties that are available in Drupal 7:

Date selection form element
Filter granularity
Starting year
Ending year

I installed these modules, but none of them fixed the problem:

views_block_filter_block
better_exposed_filters

Any idea or hint?


texts: Theming/Aligning Multiple Views Blocks on Homepage

texts:
I have an article content type which has a category field that is an entity reference field type linked to a taxonomy group of terms I created.

The website has 6 different pages which are just a taxonomy view based on the 6 different article categories listing the articles that are associated with that category. These are the settings of the taxonomy view used for each of the pages:

What I'm trying to do is create 6 block views on the homepage in a grid where each block view is a different category title showing the 4 most recent article titles and a more button to take you to the listing page of said category view. Each background would be a different image based on my CSS. This is what I'd like it to look like:

I'm using Boostrap so what I'd like is each row to be put within a
 and then each block to have a
.

What I want the final code for each block to look like is the following:

{{ category.title }}

Article Title 1

Article Title 2

Article Title 3

Article Title 4

        More

I know I could create a different block view in views for each of these (would that be the best practice?) and then place them in the content region only on the homepage but then how would I theme the template files so that I could have them work the way I've shown above?

Is there a better approach to this than what I'm suggesting above? Any help/suggestions is greatly appreciated. Also, if something exactly like this has been asked/answered before, a link to that would be helpful as I've tried searching on here and haven' been able to find anything exactly like my issue.


texts: How to go about creating location selector: a languages like "countries" global variable?

texts:
I'm interested how should I approach creating a language switcher like countries switcher?

The idea is that I wish to have country specific content and restrictions (just like with languages) but I want to allow all languages for every country.

Ideally I'd need to have the country value as a global variable and even in the cookies. A great bonus would be if I could assign it to the url like languages (../en/.. -> --/us/en/..) without ruining routing for core or path auto/url aliases etc..

But I don't know how and where to start and can't even find materials on people having done anything similar before.

My train of thought here would be the following:

Create custom module

Create a countries database/list
Set the country as a global variable somehow
Set the country as a cookie and fetch on every page load (or if possible to and from url)
Create the selector widget

Any ideas how to better understand what I'm facing and recommendations for tackling this? Also a lot of big corporations have location selectors with that locations languages which restrict content, how is this not possible with Drupal? (Couldn't even find anything for D7)


texts: Updating taxonomy vocabularies with Rules?

texts:
I'm wondering if there's a way to add/edit/delete Taxonomy terms in a Rule with Drupal 7? I haven't found any way to define an action that will let me do that.

Usecase: I'm trying to use Rules to maintain a vocabulary of usernames of a certain role, so when a user's role is updated I add/remove their username.


texts: Date field in view Filter Criteria, where date may be blank

texts:
I have a date field attached to a content type and it's not a required field. I want to use this date to control the display of the content using a view and it's filter criteria.

Some content may have blank dates and some may have a start and end date.

Is there a way I can set up the view to check for all of these conditions?

content is published
AND content type is TYPE
AND Start date is blank OR Start date is not blank AND start date is <= NOW
AND End date is blank OR End date is not blank AND end date >= NOW


texts: How obtain the Distance/Proximity between 2 fields?

texts:
I am working on a project (Omega subtheme) with Panels and Views. I'm trying to create a list of local secondary schools and their distance from a few locations.

Installed Location Module, enabled it, together with Location Search, Location Taxonomy, Node Locations and Location CCK. Also, imported list of zipcodes for my location (gb) into database.

Next I created Content Type ‘secodnary school’ with School Location field, containing Address ,Postal Code, City, Country, and Latitude and Longitude fields.

Then I created 3 pieces of content – namely 3 local schools (to start with) with their addresses and lat/long info.

Finally, I tried to create a view that will contain the above list of secondary schools, sorted by their proximity to the given location and to connect it to a different piece of content (page) that holds the location info (address, postcode, latitude/longitude) of different (X,Y,Z) locations.
X, Y, Z (…) are pieces of content (pages) of XYZ content type that among other things contain their individual location info.

So I need my new view (lets call it distance_sec_schools) to pick up location info from it’s host (XYZ) content  (hint: I tried to configure CONTEXTUAL FILTER – content NID to provide content ID from URL – but it didn’t do the trick) and then provide me with the distances to 3 local schools, which I will then sort by proximity criteria.

Take a look at the screenshots of my view and Location: Distance / Proximity - Field Settings (framed red) and Filter (framed blude), which I suspect might be where my problem lies.

At the moment, my view produces a table with the school names but without the distances.


texts: selecting hierarchical select values during migration

texts:
I want to select the values of a taxonomy which is being shown by heirachical select. These values are to be selected while importing the data through csv by  using migration module.
right now i am passing the values but it not picking up the hierarchical select list.
Any help would be useful..
thanks


texts:
I've managed to get my webform fields to display in views via this tutorial. The tutorial uses the Webform My SQL views and data modules.

Webmform My SQL views: 7.x -1.0
Data: 7.x-1.0 alpha

System:
Plesk 10.3
CentOS 5.8
Apache 2.2.3
Php 5.1.6

I can successfully create my view that allows me to choose the webform fields I want to display, however, when i try to add the "Webform views request time off 272: Submitted" date field, I get this:

  Warning: date_timezone_set() expects parameter 1 to be DateTime, boolean given in format_date() (line 1909 of /var/www/vhosts/mydomain.com/intranet/includes/common.inc).

  Warning: date_format() expects parameter 1 to be DateTime, boolean given in format_date() (line 1919 of /var/www/vhosts/mydomain.com/intranet/includes/common.inc).

As a result, this field displays no values.

I've done a search on that issue and while I did find some topics, I'm not sure how they apply to my situation. Unfortunately, this site is for our intranet so I cannot post a link.

The goal in this view is to show the submission fields and include a filter control that I can expose to the user that uses the submission date as the criteria for a date range.

I had the "Date" module activated, then deactivated which didn't resolve the issue.

Any help would be greatly appreciated.


texts:
Can the Devel page generation times be placed at the top of the page?.

Devel places the page timer and memory usage  figures at the bottom of the page making it necessary to scroll down to view them.

Is there some setting to place it below at the top, either above or below the page header?


texts: Incorrect string value: '\xF0\x9F\x92\x99' for column "'comment_body_value'"

texts:
How can I fix the following error I get from a Drupal 7 site?

Incorrect string value: '\xF0\x9F\x92\x99' for column "'comment_body_value'

I read it is about users posting emojis that cannot be handled by Drupal/MySQL.
I don't care if the comments are being stripped off the emojis, or converted as long as it does not trigger an error to the end-user. The simpler the solution the better.
I found a few modules, for example the Emoji Scrub module that isn't covered by the security advisory policy.


texts:
I am using search API on my website (Version 1.8), I have a problem with indexing custom fields. In the Configuration -> Search and metadata -> Search API I have added the custom fields to be indexed, in the view in the "Fulltext search" the custom fields appeared. In the database I can see that the fields got indexed. But when I test, there is no result. Has anyone had similar troubles with Search API?

Edited: The problem occurs only with the fields of "Entity reference" type


texts: How to create an editable table (by users) from Webform submission data?

texts:
I'm using D7 and creating a system to manage information about a specific game's characters. I have been advised to use webforms to collect the data from the character's, and I want the user that fills out those webforms be able to edit the data, just like they would on an Excel table.

I've been looking and looking and haven't been able to find an answer to how to get it done.

Any help?


texts: 'Page not found' but hook_menu() is correct!

texts:
This is my hook_menu:

$items['events/%event'] = array(
  'title' => 'Event',
  'title callback' => 'entity_label',
  'title arguments' => array('event', 1),
  'page callback' => 'events_view',
  'page arguments' => array(1),
  'access callback' => 'entity_access',
  'access arguments' => array('view', 'event', 1),
  'file' => 'events.pages.inc',
);

return $items;

But when I navigate to events/2 there's a 404 error waiting! Here's the page:

As you can see, my Event has been successfully created (it exists in database and its id is definitely 2) but the requested page could not be found and Shortcuts menu and Navigation block has disappeared.
What possibly could I mistaken?
Feel free to ask for more information.
Thanks.

EDIT:
I'm using Drupal 7.12


texts: I am unable to edit the  tag on any of my product pages, however, I am able to edit on all other pages. The Page Title option or slot is not even shown on the edit of my products. I have the Page Title module (6.x-2.5) uploaded and enabled. Any ideas?


texts: How to iterate thru a webform checkbox results

texts:
How do you iterate thru a webform checkbox array like so :

Checkboxes_name :
☒ option 1
☒ option 2

[webform_submission:values:checkboxes_name_:value] print :

option 1, option 2

I would like to have

- option 1
- option 2

I tried something like this and other variants, but no luck :

<ul{{ webform_token('[webform_submission:values:checkboxes_name_', webform_submission)}}>
  {% for item in webform_submission.values.checkboxes_name_ %}
    <li>{{ item.value }}</li>
  {% endfor %}
</ul>

Thanks for your help


texts: Is there any way to get the view object in views-view-grid-page.tpl.php

texts:
Here is the views-view-grid-page.tpl.php code:

<?php

/**
 * @file
 * Default simple view template to display a rows in a grid.
 *
 * - $rows contains a nested array of rows. Each row contains an array of
 *   columns.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>
<table class="<?php print $class; ?>"<?php print $attributes; ?>>
  <?php if (!empty($caption)) : ?>

<?php print $caption; ?>

  <?php endif; ?>

    <?php foreach ($rows as $row_number => $columns): ?>
      <tr <?php if ($row_classes[$row_number]) { print 'class="' . $row_classes[$row_number] .'"';  } ?>>
        <?php foreach ($columns as $column_number => $item): ?>
          <td <?php if ($column_classes[$row_number][$column_number]) { print 'class="' . $column_classes[$row_number][$column_number] .'"';  } ?>>
            <?php print $item; ?>

        <?php endforeach; ?>

    <?php endforeach; ?>

I need to do some modifications on this code and in these modifications I have to get the loaded view object and it's properties. Is there anyway to do this?

Unfortunately dsm($rows) doesn't give me the object it only display set of html tags.


texts: Modal Window won't close after loading a new page in it

texts:
Having weird problem in Drupal 6.  We are loading a modal window that searches for places.  The results are displayed, then someone clicks on one of the results, the parent window places that info into a field there.  Then the modal window closes.

I'm using:

Drupal.modalFrameChild.triggerParentEvent('childClose', false); return false;

to close it.

To refer to the parent window fields, I use

parent.parent.getElementById('<field>').value = "";

This is working fine.

There is a link at the bottom that allows you to add your own business if you cant find one in results.  This loads a NEW page within the modal window.  Once everything is added and submitted, I run the same javascript code.  All the parent.parent pieces work, but the close window one doesn't.

I get this error: Uncaught TypeError: Cannot call method 'eventHandlerName' of undefined

Anyone had this issue?  Does loading a new page into the modal window cause it to lose the parent/child connection?  I'm at a loss...


texts: Any suggestions for Taxonomy scaling and performance with 1073 terms?

texts:
I manage a website where the owner categorizes everything via taxonomy. However, he's extremely detailed when it comes to categorizing things. He has 1073 taxonomy terms, about 1000 of which are in one single vocabulary. The node edit screen takes 10-15 seconds to load!

I've told him he needs to consolidate but he's not going to.

Does anybody have any advice for performance tuning? Changing to the ajax autocomplete control isn't an option because he needs to be able to see the hierarchy.


texts:
I want to overwrite the $link['text'] value in theme('rate_button', $link['text'], $link['href'], 'rate-btn'), a theme function defined from the Rate module, under a specific content type in template.php. Is there a way to get that? How can I do that?

function rate_preprocess_rate_widget(&$variables) {
  extract($variables);

  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', $link['text'], $link['href'], 'rate-btn');
    $buttons[] = $button;
  }
  $variables['buttons'] = $buttons;

  $info = array();
  if ($mode == RATE_CLOSED) {
    $info[] = t('Voting is closed.');
  }
  if ($mode != RATE_COMPACT && $mode != RATE_COMPACT_DISABLED) {
    if ($results['user_vote']) {
      $info[] = t('You voted \'@option\'.', array('@option' => t($results['user_vote'])));
    }
  }
  $variables['info'] = implode(' ', $info);
}

This is the code of theme_rate_button().

function theme_rate_button($text, $href, $class = NULL) {
  static $id = 0;
  $id++;

  $classes = 'rate-button';
  if ($class) {
    $classes .= ' ' . $class;
  }
  if (empty($href)) {
    // Widget is disabled or closed.
    return
      '' .
      check_plain($text) .
      '';
  }
  else {
    return
      '' .
      check_plain($text) .
      '';
  }
}

The reason I am asking is that I have installed the rate module, and created the emotion vote (only one), which is used in two content types ("story", and "company"). In the "story" content type, the vote button should show two buttons labelled "best" and "bad," but in the "company" content type I want to set the buttons to "up" and "down."

The local variable $links used in rate_preprocess_rate_widget() contain the data for two buttons, of which I want to change the label basing on the content type of the node where those buttons appear.


texts:
This module is able to send emails to subscribers. User has to click a download link (included in an email) and will be redirected to a download page. After that he/she need to click the link to open the file. Lastly, save the files to their computer.

Here is my question: Is there any way to click the download link from his/her email and download the files immediately?

More Info: I think Email Download Module is what I need, however it is only use for drupal 6.


texts: why doesn't system_menu() return the option I am expecting

texts:
If you go to this website: https://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_menu/7

You will see what system_menu is supposed to output. My Drupal 7 has a jquery update under the development menu in the configuration tab. Why doesn't the jquery update option show up? Is there another function that I should be looking at?

Thanks!


texts: View add a new field it can't find the fields "All disappeared "

texts:
Something strange happened to my website and suddenly all the fields disappeared from view.

I tried to create new view with content type building. the building content type has the following fields Title, photos,address,building ready,price,description and logo.

at the time of creating the view I can find all the above fields and can add them without any problem  but after few minutes the fields disappears from view and going back to add field only few common fields are available

Going back to view i can see a message "This view has been automatically updated to fix missing relationships. While this View should continue to work, you should verify that the automatic updates are correct and save this view."

During creating the view all the field are available

creating new view configuration screen

I tried to update Drupal noting changed

I tired to update Views noting changed

I tired Registry Rebuild noting changed


texts:
I have a custom form. On an element on the form I have an ajax callback:

  $form['test'] = array(
    '#type' => 'textfield',
    '#title' => t('test'),
    '#ajax' => array(
      'callback' => 'test_ajax',
      'wrapper' => 'rainbow',
      'method' => 'replace',
      'effect' => 'fade',
    ),
    '#prefix' => '
',
    '#suffix' => '
',
  );

My callback function is:

function test_ajax($form, $form_state) {
  $form['test']['#suffix'] = '
Test

';
  return $form['test'];
}

When the ajax event is triggered Test is added to the element as a suffix.

If I then press enter to submit the form and a validation error occurs the suffix reverts back to the original value meaning I lose my message.

Looking in my custom validate function I can see that the $form object has the original suffix. Editing the suffix here makes no difference to the display.

I have also tried adding the following to my validate function.

  $form_state['rebuild'] = TRUE;
  $form_state['flag'] = 1;

However the original suffix is still displayed.

How can I get modified suffix to remain?


texts: How do I display serialized 'REST Export' with date format rather than timestamp?

texts:
I am using csv_serialization contrib module to add csv encoding to the core Serialization output formats.

I have a view with a REST export display to allow the download of contact form 'message' entities, and as each contact form might have different fields I must return a (serialized) Entity rather than Fields (with the option to configure each field's display).

The resulting csv download lists created date as a unix timestamp and I need to format it as a human readable time and date, but as far as I can see the 'REST export' does not go through rendering so I cannot preprocess it in the same way I might with a different type of Views display.


texts: How can I add content in between views in bootstrap grid format?

texts:
How can I add content in between views in grid format?

Header and footer is fine, but how about interrupting the flow of grids, is there a module for that?

Or do I need to hard code a template file?

Or maybe use css to make the element full width at X item number in the grid?

Image to explain here:


texts: Show certain elements based on URL query string

texts:
I am very new to drupal and also very willing to learn.
I am trying to migrate old code from another tool to drupal 8.
I am working on a form, using the webform module.
Can I possibly show certain webform elements based on specific URL query strings?
Example:
test.com?user=employee, then show TextField = employee ID
test.com?user=customer, then show Textfield = Company name.

Any help would be greatly appreciated.


texts: How to use Rules to email users when any field(s) is changed in a node (and include the unchanged/changed values for that field)?

texts:
I know how to email using Rules when a field in a node is changed and add conditions for particular fields whether they were changed.

But I would like the email to contain the info which field(s) exactly were changed and from/to which value.

E.g., I have a content type with 20 fields. Then I create a node and populate all the fields. Now I want to change two fields in the node (e.g., "First Name" and "Age").

I'd be happy to receive the following email:

The following was changed in "Node name":

"First name" changed from "John" to "George".

"Age" changed from "35" to "76".


texts:
How do I configure HoneyPot module spam blocker to work on my comment pages for my Advanced Forum?

I enabled the Honeypot in Config section, checked Blog entry node form and Forum topic node form in Node Forums and Comment Forms.


texts: How do you programmatically get the current user's status?

texts:
I'm trying to get the currently logged-in user's status (active or blocked) in template_preprocess_user. I tried the following with no luck.
function MYTHEME_preprocess_user(&$variables) {
  $user = $variables['user'];
  $variables['status'] = $user->status();
}

function MYTHEME_preprocess_user(&$variables) {
  $user = $variables['user'];
  $variables['status'] = $user->getStatus();
}


texts: I just want to get the user information who create a new menu item under menu section.  I am not able to get any entry in database regarding the menu creator (UID). There is a entry in {menu_links} table, but in this table or any other table there is no UID linked.


texts:
I can't authenticate with Drupal 7 and Services module.
From REST client I send POST {"username":"username, "password":"password"} to user login endpoint.
I get sessid, session_name, token and user object.
I form header like:

Cookie: "session_name = sessid";

X-CSRF-Token: "token"

and after making GET to node I get:
["Access denied for user anonymous"]

What am I doing wrong?


texts: How to pass variable to a views template?

texts:
I have this in my template.php:

function mytheme_preprocess_views_view(&$vars) {
$vars['test'] = 'Filtertest';
}

And this in my views-view-responsive-grid--taxonomy-term.tpl.php:

<?php print $test; ?>

... this does not work though. The template is called and works but my $test variable does not get printed.

What am I missing here? Any help is greatly appreciated.


texts:
I am seeing this error in my logs:

Theme hook MENU_CALLBACK not found

What are the causes? I cannot find this exact phrase in google or d.o. This is an example menu item:

$items['user/%user/integration/%integration'] = array(
    'title' => 'View An Integration',
    'page callback' => 'integration_view_page',
    'page arguments' => array(3),
    'access callback' => 'is_owner',
    'access arguments' => array(1, 3),
    'type' => MENU_CALLBACK,
);

Yes, cleared caches, including menu cache. The actual page appears to load ok.


texts: I know I can upgrade my account and have Pantheon do it for me but I want to explore the possibility of writing a bash shell script which uses Terminus commands to backup all my Drupal sites so that I can add to cron on my own schedule.


texts:
I had Drush working yesterday and was able to use it to download a copy of Drupal. After shutting down my machine last night it now won't work.

which drush does nothing today. drush help gives: -bash: drush: command not found

I guess that when I installed it yesterday, some setting was live in the terminal allowing it to work, but this wasn't saved or stored so after restarting it doesn't work. On the day drupal was installed I closed and reopened the terminal window several times and Drush kept working.

I can still see my copy of 6.5.0 in $Trotter/.composer/vendor/drush/drush/

The installation instructions say:

  Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users)

I followed these instructions on creating a bash profile and have saved my bash profile with the single line in it:
export PATH="$Trotter/.composer/vendor/bin:$PATH"

Following the instruction below in terminal didn't do anything for me:

  Type ". .bash_profile" to reload .bash_profile and update any functions you add

Please suggest what I need to do to get Drush working again, and keep working after restarting the machine.

Here is the location of composer inside my home directory:


texts: How to always get distant ancestor reference when loading descendent?

texts:
I have a fairly large website with some complex relationships. One such string of relationships looks like this:

region > counties > cities > locations > contacts

Each level is the name of a content type. Each level is a parent with many children (except the last) connected via simple Entity Reference fields.

The region content type is central to the entire site. Users, custom permissions, custom layouts, every content type – it all revolves around the region in some way.

I have dozens of views on this site and as you might expect things get pretty ugly when trying to find out what region any of the descendent content types are associated with. To find the region for a given contact for instance, the relationship looks like this:

location for given contact >
city for given location >
county of given city >
region of given county

I'm really getting tired of making these long relationship trees in views. Of course, outside of views, I can write a function like load_region_by_contact or something, but I'm using the views UI quite a bit and I can't seem to find any way to store this set of relationships (and others) in a way that I can repeatedly reuse.

The data itself doesn't change too often and can be heavily cached, so I'm not opposed to the 'views of views' solution. I just don't know how to build it.


texts: I am trying to build a new theme. Are blocks a OK way to model a theme? Some sites seem to recommend them, others say that they should be avoided.


texts: Is there a way to limit the operators for views-filtering for users. I want them to only have "starts-with", "contains" and "same". But not the rest. Do I have to form_alter with a custom module? Or is there some intern way to achieve that?


texts:
I'm writing a module that use Taxonomy terms for different data (cast, directors, ... of a movie). Now I prefill some default fields to a create node page using the hook_form_alter. The only prefill that doesn't work is the taxonomy terms.

The code that I tried for prefilling taxonomy term looks like:

$directorIndex = 0;
    foreach($movie->directors as $director)
    {
        if ($directorIndex > 0) {
            $form['field_movie_director']['widget'][$directorIndex] = $form['field_movie_director']['widget'][0];
            $form['field_movie_director']['widget'][$directorIndex]['#delta'] = $directorIndex;
            $form['field_movie_director']['widget'][$directorIndex]['#weight'] = $directorIndex;
        }

        $form['field_movie_director']['widget'][$directorIndex++]['target_id']['#default_value'] = get_vocabulary_term($director['name'], 'movie_director');
    }

function get_vocabulary_term($term_value, $vocabulary) {
  if ($terms = taxonomy_term_load_multiple_by_name($term_value, $vocabulary)) {
    $term = reset($terms);
  }
  else {
    $term = \Drupal\taxonomy\Entity\Term::create([
      'name' => $term_value,
      'vid' => $vocabulary,
    ]);
    $term->save();
  }
  return $term;
}

The fields are created on the form and are filled in.But when saving the form the values are lost and only the first value of the taxonomy term field has been saved. How to fix this to save the form with all the fields?


texts: In views, how can you link "read more" to the webform submission?

texts: I have created a view from webform submissions but some of the answer in the submission are too long. I tried to add a "read more" link in the view to be able to view the rest of the answer but I'm not sure which path to give it. When I do node/[nid], as you would with a content type, it goes back to the blank webform.


texts: What is the appropriate way to keep php variables

texts:
For persisting variables in my module (without using the db) I have these options:

variable_set/variable_get - for general use
drupal_static - should be used for static variables
define - should be used for constants

Is this an accurate summary? Are there other methods I'm missing?


texts: Auto assign organic group to a content type

texts:
I'm trying to assign the group audience to a content type at creation instant. The first thing I have done is to disable the group audience field. So I have implemented the hook_form_alter and done this:

$form['og_group_ref']['#access']= false;

Then, I have implemented the hook_node_insert and here is where I have tried to assign the group. In my use case, users can only have one group. That's my code:

/**
 * Implements hook_node_insert
 */
function og_autoassign_node_insert($node){
  //Get the type
  $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

  if ($type == 'content_type1' || $type == 'content_type2'){
    // Get the user
    $user = user_load($node->uid);

    // Load the current user's group
    //$groups = og_get_entity_groups('user', $user);
    $groups = og_get_groups_by_user($user);

    // Load the GID
    $group_id;
    foreach(array_keys($groups['node']) as $id){
        $group_id = $id;
    }

    $values = array(
        'entity_type' => 'node',
        'entity' => $node,
        'field_name' => 'og_group_ref',
        'state' => OG_STATE_ACTIVE
    );
    og_group('node', $group_id, $values);

    dpm($node);
  }
}

When I print the node with dpm, I can not see the organic group associated. What I'm doing wrong? Can anyone help me?

Thanks a lot

UPDATE (I can't answer myself because I have less than 10 in reputation)

Well, I found one solution. Instead of implementing the hook_node_insert, I did that in my hook_form_alter:

function my_module_form_alter(&$form, &$form_state, $form_id){
...
// Load the current user's group
$groups = og_get_groups_by_user();

$form['og_group_ref']['und'][0]['default']['#default_value'] = $groups['node'];
}

And that set the field "Audience Group" with the user's group.


texts:
I would like to be able to custom theme a region for specific pages, is this possible? If so how?

For example I have a ragion called rightbar and I know the region can be themed using region--rightbar.tpl.php but is there a way of theming this using something like page--node--1--region--rightbar.tpl.php?

Or am I going to have to condition the region--rightbar.tpl.php script?


texts: Token does not return full dynamic path to Media Image URL

texts:
I'm having trouble configuring Metatag for Open Graph and Twitter Card images.
I'm using Drupal 8.9 core Media Image reference field as the source.
[node:field_hero_image] (Entity reference field) just returns the bare filename.
[node:field_hero_image:entity] (The referenced entity) also returns the bare filename, not the expected path to the image.
[node:field_hero_image:target_id] Just returns an integer. (In this case, it is 1.)
I'm reduced to trying to build the path by combining Tokens and plain text, like this:
[site:url]sites/default/files/2021-01/[node:field_hero_image]

This works, but the problem is that I used the default File Directory path:
[date:custom:Y]-[date:custom:m]

That means media assets that I upload in February will be at a different path than the ones I uploaded last month, so hard-coding the path to the directory is pointless.
Now, I could change the File Directory path to a const str like images, delete all my Media Images and recreate them.
I'm guessing there is a better approach: either a Token that returns the correct image URL, or a way to bulk reconfigure Media Image assets after moving their File Directory.
Please help!


texts: twig to print paragraph field in controller

texts:
new to d8. I have a result page where I need to print the field values of a paragraph field into my controller. The paragraph field is called field_classrooms.

text values print fine for example
{{ teacher.field_last_name.value }}

but when I need to print
{{ teacher.field_classrooms.value }}

I get

  User error: "target_id" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).


texts: Create dummy instances of custom entity with dummy field data?

texts:
My module defines a custom entity type and bundle and adds fields to the bundle programatically. Now, I need to create a bunch of dummy data to test the interface. I'm working with various combinations of entity_get_controller()->create(), entity_metadata_wrapper()->save(), field_attach_submit(), etc. and I have been able to fill the entity base table with new rows. The problem is that the generated entities aren't loaded with:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'my_entity_type');

I'm not surprised that the query doesn't return my new entities because I haven't found a place to specify bundle for the dummy entities and I haven't figured out how to generate default or random field data. How do I specify the bundle for my new entities and how can I generate valid random field data for date, taxonomy_term_reference and integer fields?


texts: Location module should lookup address before saving

texts:
This question is related to Adding geo location content to node.
I'm trying to get a location saved to a node. The Location module supports this, but I don't like the workflow of this module.

It does the look-up after the node is saved, but I would rather do the location look-up before the node is saved, e.g. by having a look-up button that, when pressed, queries Google, updates the gmap, and lets the user see the location before saving and not afterwards, which causes troubles, if the input address couldn't be found.

Do you have any idea on how to address this issue?


texts: how we could use display suite to manage the display blocks on regions?

texts: I want show 2 blocks inline inside the "Top bar" region. is It possible use, for example, the layout "Bootstrap Two Columns: 6-6" in region?


texts:
I'm working the SchemaAPI but can't get it to create the tables. This is the content of my schema_test.install which is mostly copied form the examples modules.

<?php
function schema_test_install() {
  drupal_install_schema('schema_test');
}
function schema_test_schema() {
  $schema['schema_test_one'] = array(
    'description' => 'Stores example person entries for demonstration purposes.',
    'fields' => array(
      'pid'  => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique person ID.',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => "Creator user's {users}.uid",
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the person.',
      ),
      'surname' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Surname of the person.',
      ),
      'age' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => 'The age of the person in years.',
      )
    ),
    'primary key' => array('pid'),
    'indexes' => array(
      'name'    => array('name'),
      'surname' => array('surname'),
      'age'     => array('age'),
    ),
  );
  return $schema;
}
/* vim: set ts=8 sw=2 tw=79 cc=80 ft=php:*/

I also have the Schema Module enabled and it lists this schema under "Missing". So it's recognized but never installed when the module is being enabled. What am I missing here?


texts: Is it ever okay to ignore a warning about an inconsistent Database schema?

texts:
Can it ever be ok to ignore a Database schema = Inconsistent report?

The schema module is reporting the following mismatches:

contact

page_title: unexpected column in database
page_info: unexpected column in database

search_dataset

column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

search_index

column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

search_node_links

column type - difference on: length
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE, 'default' => '')
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')


texts:
EDIT: Still need some help with this. It seems the value of "$form_id" is nothing related to "webform_client...". When I echo the value of $form_id in the mywebform_extra_form_alter() function it outputs a value of: "search_form_block".. nothing indicating a webform.

Can I ask for some more assistance with this?

I've created a module for a webform submission hook to open and modify a CSV with the submitted values:

function mywebform_extra_form_alter(&$form, &$form_state, $form_id) {
    // Add validation for a particular Webform node:
    if ($form_id == 'webform_client_form_213') {
    // Add the submit handler after the existing Webform submit handler,
    // but before the second Webform handler. Pop off the first one and add
// ours second.
    $first = array_shift($form['#submit']);
    array_unshift($form['#submit'], $first, 'mywebform_extra_submit_213');
  }
}

function mywebform_extra_submit_213(&$form, &$form_state) {

    global $user;

    // Changes can be made to the Webform node settings by modifying this variable:
    $form['#node']->webform;

    $name = $form_state['values']['your_name'];
    $email = $form_state['values']['your_e_mail_address'];
    $zip_code = $form_state['values']['zip_code'];
    $date = date('m/d/Y');

    $handle = fopen("pledge_submissions.csv", "a");
    $line = array($name,$email,$zip_code,$date);
    fputcsv($handle, $line);
    fclose($handle);

}

It seems these functions are firing but when I open the CSV, no data has been added.

Is $form_state['values']['field_name_here'] the correct way to target the webform field values? When I try to alert things inside that function the form errors out after submission.


texts: Why can't I add an existing field to the user accounts on Drupal 8?

texts:
On Drupal 7, you can add fields that have been added to nodes to user accounts.  At admin/config/people/accounts/fields, scroll down to Add related fields and simply select the field, easy.

But in Drupal 8, at /admin/config/people/accounts/fields, I see no option to add an existing field, just Add Field, which adds a new field.

Has this option been removed from Drupal 8, and if so, why?


texts: I lost custom fees when apply pricing rules

texts:
I'm using commerce fees modules to add fees when I create orders manually from the backoffice, but click when I click apply pricing rules I lost the added fees. If I add fees (custom fees line item) after applying pricing rules, the VAT taxe be applyed to the unit price only.
Any help please.


texts:
If you have a sub-theme of a sub-theme...

Sub-theme a
Sub-theme b (base theme = Sub-theme a)

Ideally, what I want to do is have the default theme as 'Sub theme a' and just introduce some minor theming and processing in 'Sub theme b'. Reason being, there are lots of versions of this site being deployed and some minor fixes are required that can be thrown away at the click of a button i.e. remove Sub-theme b.

Google has not been helpful in this instance ;-)

If both themes are enabled and sub-theme a is the default, how do I get sub-theme b to work? (because its not working i.e. I have added a stylesheet in the .info file and its not being added. If I make sub-theme b default then Sub-theme a doesnt work)


texts: How do you change the default sort in apachesolr?

texts:
I've been trying to get this figured out for a couple days now, and I feel like I'm close, but as of yet no cigar. I need to make the apache solr search on the site I'm working on to have two sorts, 'created' and 'score'. The default search sort is score, but I need to change it to created.

I've got as far as changing the default itself, but then change is added unconditionally, so obviously it will always occur over score. Do I have to rebuild all the URLs to use arg, or is there an easier way? Here's my code:

Note: there's some code to remove some filters, but that's not related to the problem. I included them just in case.

   function myhook_apachesolr_prepare_query(&$query, &$params) {
     // Remove sorts
     $query->remove_available_sort('type');
     $query->remove_available_sort('sort_title');
     $query->remove_available_sort('sort_name');
     // Rename/Reorder sorts
     $query->remove_available_sort('created');
     $query->remove_available_sort('score');
     $query->set_available_sort('created', array('title' => t('Most Recent'), 'default' =>     'desc'));
     $query->set_available_sort('score', array('title' => t('Most Relevant'), 'default' => 'asc'));

     // Change the default sort to by date
     $query->set_solrsort('created', 'desc');
   }


texts:
I would like to let users create elements with no title.

In this particulary case, I would like them to enter a registration number, as you can imagine there's no need for a title right here.

How can I remove it from the creation page (node/add/node-type),  so I can only see the fields I want (not the title)?


texts: Best practice to have a 'category' fields where admin can choose wich voices the user can choose

texts:
I have a content type that needs a 'category' field; this can both be a taxonomy vocabulary or a text field (with the select widget), it doesn't really matter. (I won't have more then 5-6 voices at once.)

However, those voices may change over time, and normal users should be able to choose only few values when creating a new node.

What is the best practice to achieve this?

My idea is to use a taxonomy vocabulary, where only administrators can insert new voices, but I will need some kind of attribute (e.g., a boolean) that I can use in a module in order to filter them in hook_form_alter(). Could this be a Drupal-ish way to achieve that?


texts: How do I do git clone with drush to download the HEAD version of a module?

texts:
Is there any way to clone or pull the HEAD version of a module in drupal.org git repository?

For example, if I'm on Drupal 7, and the last branch of Views is 3, I would like to do:

drush git-clone views

to achieve something equivalent to:

cd sites/all/modules/
git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git

Ideally, using drush git-clone views-3x should clone the 3.x branch explicitly.

Is this possible or am I dreaming? This would be really useful for developing.


texts: Panels doesn't output views content pane title

texts:
I have a panel named bar in which I added a view-content-pane named foo.For this view I created a template-override named views-view--foo--panel-pane.tpl.php in which I added, besides other things, a container for the $title like:

<?php print $title; ?>

The title of the view-content-pane is Foo.
To limit the moltiplication of divs I set to "No markup at all" the style of both the whole panel and the single pane.
Configured like that, the view shows with custom styles (which I setted in my custom theme-override) except for the title that doesn't display at all.
If I change the single pane style to "No style", the title is shown but using the panel default style (which breaks my layout).

It's there a way to output the view-content-pane title as configured in the template-override without this being rendered by the panel?


texts: Spacing with inline links in TranslatableMarkup

texts:
I have a TranslatableMarkup string that has a link that is inserted in it as a variable. However this link comes without a space between the link and the previous word in the string.

$message = new TranslatableMarkup("Some message and last word @link", ["@link" => $link]);

This message is then printed out using drupal_set_message. The message comes without the space between 'word' and the link when it is displayed.

This is the expected behaviour with browser ignoring the white space before the  tag with the link. How do we force this without custom inline block styling for the link?


texts: Check if the connection to the database is available

texts:
I have 2 databases, the first one with Drupal and the second one with external data. In a controller I want to read data from that second database and display it.
As the external database can be available or not, is there any method to check if the connection is available or not?
My code is working, but if the DB is not available (or unset) I get the following error:

Drupal\Core\Database\ConnectionNotDefinedException: The specified
database connection is not defined: schedules in
Drupal\Core\Database\Database::openConnection() (line 364 of
core/lib/Drupal/Core/Database/Database.php).

Code:
abstract class AbstractSchedulesRepository {

  /**
   * Schedules repository target.
   */
  public const SCHEDULES_REPOSITORY_TARGET_DATABASE = 'default';

  /**
   * Schedules repository key.
   */
  public const SCHEDULES_REPOSITORY_KEY_DATABASE = 'schedules';

  /**
   * Drupal\schedules\Repository\SchedulesCache definition.
   *
   * @var \Drupal\schedules\Cache\SchedulesCache
   */
  protected $schedulesCache;

  /**
   * Drupal\Core\Language\LanguageManager definition.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

  /**
   * Drupal\Core\Database\Connection definition.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * Constructor.
   *
   * @param \Drupal\schedules\Cache\SchedulesCache $schedulesCache
   *   Schedules cache.
   * @param \Drupal\Core\Language\LanguageManager $languageManager
   *   Language manager.
   */
  public function __construct(SchedulesCache $schedulesCache, LanguageManager $languageManager) {
    $this->schedulesCache  = $schedulesCache;
    $this->languageManager = $languageManager;
    $this->connection      = Database::getConnection(self::SCHEDULES_REPOSITORY_TARGET_DATABASE, self::SCHEDULES_REPOSITORY_KEY_DATABASE);
  }


texts: I want to allow users to click "share this" on a page with an image, and then email that image as an attachment

texts: I have a site that shows floor plans for houses. I want to allow users to share a floor plan via an email form where they can enter their email address and their friend's email address who they want to share with. Then when they enter their message and submit, the image of the floor plan will be attached to the outbound email from the server.


texts: How can I check in Drupal 8 an externally set $_COOKIE?

texts:
I would like to check whether a Cookie exists, and if so, get the value. But it looks like Drupal is blind to external cookies that have not been set inside Drupal.

$mycookie = \Drupal::request()->cookies->all();

Returns an array with only the Drupal cookies, and I can see in my web browser that there are more (some that I am interested in and I can't modify he app that is creating those cookies). I remember there was a similar issue with Symfony 2 and session but I can't find it...


texts: Translatable image field gets replaced when adding content

texts: I have added an image field with Translatable Content enabled. My content type has enabled translations too. But when I add an image in the translation, the english contents field get replaced with the newly added translated image. (English is my base language, and I have Japanese and Chinese as translations). This happens vise versa too. What could be the issue?


texts: How to sort nodes per domain with the Views module?

texts:
I have to display nodes in different order(weight) inside a view per domain on a multi-domain site.

example:

on domain1: view-beverages => 1-Coca Cola, 2-Perrier, 3-Redbull, 4-IceTea ...
on domain2: view-beverages => 1-Perrier, 2-IceTea, 3-Redbull, 4-Coca Cola ...
...

I thought to use the module Flag Weights, but Flag is per user and not per domain.

Do you think I can do this by using "Draggableviews"?

Can I create a table view for each domain with Draggableviews to manage the order of the node by domain, and make the final display view chose automaticaly the "sort criteria" (Draggableviews : Weight) of the courant domain. I hope I am clear enough.

How can I do this, or there is an alternative?


texts: How to get an image URL from a field in a twig template

texts:
I have a node that contains various fields. I am able to get the values of text fields but not an image field. Below is the relevant output of the node variable being dumped in the twig template:

 'field_main_image' =>
    object(Drupal\field\Entity\FieldConfig)[1312]
      protected 'deleted' => boolean false
      protected 'fieldStorage' => null
      protected 'id' => string 'node.homepage.field_main_image' (length=30)
      protected 'field_name' => string 'field_main_image' (length=16)
      protected 'field_type' => string 'image' (length=5)
      protected 'entity_type' => string 'node' (length=4)
      protected 'bundle' => string 'homepage' (length=8)
      protected 'label' => string 'Main image' (length=10)
      protected 'description' => string '' (length=0)
      protected 'settings' =>
        array (size=12)
          ...
      protected 'required' => boolean false
      protected 'translatable' => boolean false
      protected 'default_value' =>
        array (size=0)
          ...
      protected 'default_value_callback' => string '' (length=0)
      protected 'itemDefinition' => null
      protected 'constraints' =>
        array (size=0)
          ...
      protected 'originalId' => string 'node.homepage.field_main_image'     (length=30)
      protected 'status' => boolean true
      protected 'uuid' => string 'f40a7a65-18a5-4ced-85b0-ab1cdc41b2f5' (length=36)
      private 'isSyncing' (Drupal\Core\Config\Entity\ConfigEntityBase) => boolean false
      private 'isUninstalling' (Drupal\Core\Config\Entity\ConfigEntityBase) => boolean false
      protected 'langcode' => string 'en' (length=2)
      protected 'third_party_settings' =>
        array (size=0)
          ...
      protected '_core' =>
        array (size=0)
          ...
      protected 'trustedData' => boolean false
      protected 'entityTypeId' => string 'field_config' (length=12)
      protected 'enforceIsNew' => null
      protected 'typedData' => null
      protected 'cacheContexts' =>
        array (size=0)
          ...
      protected 'cacheTags' =>
        array (size=0)
          ...
      protected 'cacheMaxAge' => int -1
      protected '_serviceIds' =>
        array (size=0)
          ...
      protected 'dependencies' =>
        array (size=2)
          ...

I have seen similar questions on SE, like this one Getting the image URL from a field_image on a node, but none of the answers have worked for me.

Thanks in advance for any responses.


texts: How do I add conditional fields to a paragraph?

texts:
I was able to add conditional fields in a paragraph, following Conditional Fields in Paragraphs Using the Javascript States API for Drupal 8, but it controls and hides only 1 field.
I need to control multiple fields from one select list. I added multiple fields to a variable and created a for loop. The select list has 3 options.

3row|3row
2row|2row
1row|1row

The following is the code for the custom module. When it runs, the last for loop is the only one that works. The first 2 select list options don't work. Do I need to add a field value check before each for loop? My module name is conditional_fields.
use Drupal\node\NodeInterface;
use Drupal\node\NodeForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\paragraphs\ParagraphInterface;
use Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget;
use Drupal\paragraphs\Entity\Paragraph;

/*
 * Implements hook_field_widget_form_alter().
 */
function conditional_fields_field_widget_paragraphs_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  $paragraph_entity_reference_field_name = $field_definition->getName();

  if ($paragraph_entity_reference_field_name == 'field_topic_paragraphs') {
    $widget_state = \Drupal\Core\Field\WidgetBase::getWidgetState($element['#field_parents'], $paragraph_entity_reference_field_name, $form_state);

    $paragraph_instance = $widget_state['paragraphs'][$element['#delta']]['entity'];
    $paragraph_type = $paragraph_instance->bundle();

    if ($paragraph_type == 'teaser_content') {
      $dependee_field_name = 'field_paragraph_number_of_rows';
      $selector = sprintf('select[name="%s[%d][subform][%s]"]', $paragraph_entity_reference_field_name, $element['#delta'], $dependee_field_name);

      $fields_to_control1 = ['field_description_col_5','field_link_col_5','field_description_col_6','field_link_col_6','field_description_col_7','field_link_col_7','field_description_col_8','field_link_col_8','field_description_col_9','field_link_col_9','field_description_col_10','field_link_col_10','field_description_col_11','field_link_col_11','field_description_col_12','field_link_col_12','field_description_col_13','field_link_col_13','field_description_col_14','field_link_col_14','field_description_col_15','field_link_col_15','field_description_col_16','field_link_col_16'];

      $fields_to_control2 = ['field_description_col_9','field_link_col_9','field_description_col_10','field_link_col_10','field_description_col_11','field_link_col_11','field_description_col_12','field_link_col_12','field_description_col_13','field_link_col_13','field_description_col_14','field_link_col_14','field_description_col_15','field_link_col_15','field_description_col_16','field_link_col_16'];

      $fields_to_control3 = ['field_description_col_13','field_link_col_13','field_description_col_14','field_link_col_14','field_description_col_15','field_link_col_15','field_description_col_16','field_link_col_16'];

      foreach ($fields_to_control3 as $field) {
        $element['subform'][$field]['#states'] = [
          'invisible' => [
            $selector => ['value' => '3row'],
          ],
        ];
      }

      foreach ($fields_to_control2 as $field){
        $element['subform'][$field]['#states'] = [
          'invisible' => [
            $selector => ['value' => '2row'],
          ],
        ];
      }

      foreach ($fields_to_control1 as $field) {
        $element['subform'][$field]['#states'] = [
          'invisible' => [
            $selector => ['value' => '1row'],
          ],
        ];
      }

      unset($element['subform']['field_paragraph_number_of_rows']['widget']['#options']['_none']);
      $element['subform']['field_paragraph_number_of_rows']['widget']['#empty_option']  = t('- 4 Rows -');
    }
  }
}


texts: Auto-complete show everything by default

texts:
I have an field of "User reference" on a content type -- using an auto-complete control. This works but our user list is in the order of 300+ and it's difficult to remember who all should be selected for various tasks.

Auto-complete by default shows a list only once you have entered a single character -- is it possible to have the list show everyone the minute you click the text field???


texts:
I watched the eva tutorial listed on the eva project page for drupal 7 and implemented that with our site. We have courses, objectives and evaluation content types. I am successfully able to attach all the evaluations to the course objective. The tutorial was great.

Since the evaluations are by semester, is there a way to add another filter by semester? I am so far unable to have the second contextual filter work on this eva view when the application is run. The 2nd contextual filter works within the view.

In the application there is a semester selection. We show all courses for that semester. Objectives for the course are displayed when the user clicks on a course. Objectives content type has entity reference to courses. Course objectives don't change by semesters, so in objectives content type there was no requirement to link to the semester taxonomy. Evaluations content type has node reference to objectives and entity reference to semester taxonomy.

I will really appreciate if someone can guide how to resolve the issue of a second contextual filter in eva view.


texts:
I am using Drupal 7 with the Print module installed.
I used this module to print nodes, but how can I print a view table?

Is there a module that I can use?


texts:
I've got a problem with CKEditor in Drupal 8. I've searched related questions like CKeditor adds extra <p> tags, but almost all questions are related to Drupal 7.

So, my CKEditor automatically applies a <p>&nbsp</p> when I hit enter and don't type anything.

How can I disable this? I don't want to remove the padding or anything of a <p> tag. I need something that checks if the paragraph is empty and then don't display it.


texts: Cannot log in my site: any idea why the session code would fail?

texts:
I have several Drupal 6 websites, most of which I can still use as normal. However, I have one where I cannot log in anymore, at least not without adding a hack to the session code.

When the code calls sess_regenerate() from user_authenticate_finalize(), it calls the function defined in the include/session.inc file as expected.

Inside the sess_regenerate() session_regenerate_id() gets called; somehow, that call generates a call to sess_read(). That function fails and resets the $user variable to the anonymous user.

My current hack is to save the $user variable in a temporary variable.

$save_user = $user;
session_regenerate_id();
$user = $save_user;

I now run with PHP 7, but I would think that's not the only problem since my other sites still work fine.

Note that I clearly verified that the normal Drupal session.inc file gets included, so it is not because those get overwritten.

Do you know of any module that could cause such a problem?

There is a list of the modules I have installed:

abuse
account_reminder
advanced_comment
autologout
automenu
auto_nodetitle
block
blog
ca
captcha
ckeditor
comment
commentmail
comment_subject
contact
content
content_permissions
content_taxonomy
content_taxonomy_options
ctools
dblog
email
fieldgroup
filefield
filter
filter_default
footnotes
forum
globalredirect
googleanalytics
hidden_captcha
hide_submit
i18n
i18nblocks
i18ncck
i18ncontent
i18nmenu
i18nstrings
i18ntaxonomy
imagefield
imce
InsertNode
jquery_ui
jquery_update
jstimer
jst_timer
languageicons
lightbox2
linkchecker
locale
login_security
logintoboggan
menu
mini
mo_anti_pounding
mo_backup
mo_feedback
mo_toolbar
mo_websites_client
nia2match
nia2match_early
node
nodeformsettings
nodewords
nodewords_basic
nodewords_extra
nodewords_og
number
optionwidgets
password_policy
path
pathauto
path_redirect
ping
prepopulate
recaptcha
role_delegation
save_draft
search
securepages
simplemenu
site_verify
spam
spam_filter_bayesian
spam_filter_custom
spam_filter_duplicate
spam_filter_node_age
spam_filter_surbl
spam_filter_url
su_comments
system
taxonomy
taxonomy_hide
terms_of_use
text
themekey
themekey_properties
themekey_ui
token
tracker
translation
translation_overview
uc_cart
uc_cart_links
uc_coupon
uc_credit
uc_googleanalytics
uc_optional_checkout_review
uc_order
uc_payment
uc_paypal
uc_product
uc_reports
uc_sisow
uc_sisowbase
uc_sisowde
uc_sisowmc
uc_store
uc_taxes
uc_tax_report
uc_test_payment
update
upload
user
views
views_data_export
views_ui
wordfilter
xmlsitemap
xmlsitemap_custom
xmlsitemap_engines
xmlsitemap_node


texts: Using feeds and xpath to import multiple images into a node

texts:
I am using feeds to import a heavily customised wordpress site into drupal using xpath and a custom xml file. All is going well until I try to import multiple images into a node.

The image field is a multi value field (not multiple different image fields)

Only the first image is imported the rest are ignored.

When I have xpath debugging on it correctly shows multiple image URI's and their titles.

Is there a way using feeds and xpath to import multiple images into a node?

This is an example of one item from the feed

<root>
    <item>
        <wordpress_id>85672</wordpress_id>
        <title>.....</title>
        <content>.....</content>
        <created>2017-03-17 10:13:24</created>
        <custom_fields>
            <url type="Website">......</url>
            <url type="Website2">.....</url>
        </custom_fields>
        <attachments>
            <images>
                <item>
                    <ID>85671</ID>
                    <post_author>0</post_author>
                    <post_date>2017-03-08 18:00:00</post_date>
                    <post_title>.....</post_title>
                    <uri>.....</uri>
                </item>
                <item>
                    <ID>85671</ID>
                    <post_author>0</post_author>
                    <post_date>2017-03-08 18:00:00</post_date>
                    <post_title>.....</post_title>
                    <uri>......</uri>
                </item>
            </images>
        </attachments>
    </item>
</root>

The post title and uri from the attachments are the two fields I am trying to map to the node image type

for my xpath I am referencing them using...

image_title => attachments/images/item/post_title
image_source => attachments/images/item/uri

and in my mapping I am using...

image_title (image_title) => Image: Title (field_image:title)
image_source (image_source) =>  Image: URI (field_image:uri)

in the  section I have no trouble mapping website and website2 to to a multi value link field so I am not sure why the image field should be any different.

edit: added xml snippet and mappings and further explanation


texts: How to set value to auto-complete field after form submission?

texts:
I have a dependent auto-complete form field in my custom module. After submission the form the auto-complete field shows above the result output. Now I want that submitted value should become default value after form submission.
I tried like this:

'#default_value' => isset($form_state['values']['keys']) ? $form_state['values']['keys'] : '',

but not getting any value. I also tried like this:

'#default_value' => isset($_REQUEST['keys']) ? $_REQUEST['keys'] : '',

but still unable to get any value. someone please help.


texts: Configuring the new display modes in Drupal 8

texts:
I like very much that in Drupal 8 you can create your own display modes (i.e. not just have "Full" and "Teaser", but create your own) and that you can reference Content via Entity Reference fields within Content. It's really neat and allows me to add arbitrary lists of content on pages and have them render as I like. EXCEPT there seems to be one small issue - the rendered entities always start with the title linking to the Content. There doesn't seem to be any way of getting around it.

Apart from creating my own templates for my display modes, is there any way I can prevent the Title displaying when I render Content in another piece of Content using an Entity Reference? This seems to be an oversight with a very useful bit of functionality - or am I missing something?


texts: How to access entity from EntityReferenceItem?

texts:
I have the attached array below and need help figuring out how to access the 'entity' attribute that is under the protected "properties" array (see screenshot).

I am using the Viewfield module

background:
field_name is an entity reference field. I need to get the EntityReference so that I can call getTarget() to get the EntityAdapter and then call EntityAdapter->getValue().

I have tried the following but they all give errors. The idea is to get the EntityReference which is the 'entity' value. How can i do this?

mytheme_preprocess_viewfield_item(&vars) {

  $element = $vars['element'];
  $results = $element['#content']['#view']->result;

  foreach($results as $row) {
    $entity = $row->_entity
    $offset = $entity->get('field_name')->offsetGet(0)

kint($entity->get($video_field_name)) /* result of screenshot */

    $entityReference = $offset->get('entity') /* failed */
    $entityReference = $offset->getProperties() /* failed */
    $entityReference = $offset->getEntity() /* failed */
    $entityReference = $offset->getValue() /* failed */
  }//end foreach
}//end theme_preprocesss

The error message is: replace getValue() with any of the above

Call to a member function getValue() on null