texts: How do i fix Invalid arguments passed in DefaultMailSystem->format() (line 23 system.mail.inc

texts:
I'm getting this error while developing a module:

  Warning: Invalid arguments passed in DefaultMailSystem->format() (line 23 /modules/system/system.mail.inc)

here's my code:

function mymod_mail($key, &$message, $params) {
    switch ($key) {
        case 'job_mail':
            $message['subject'] = 'mysubject';
            $message['body'][] = 'test';
            break;
    }
}

I googled it normaly this happens when $message['body'] is defined like this:
$message['body'] = 'test'; instead of $message['body'][] = 'test';

And then I've got the following code to call the above hook_mail()

function mymod_send_mail($vacancies, $user) {
    // specify module name and template key for hook_mail
    $module = 'mymod';
    $key = 'job_mail';

    // Specify to and from addressses.
    $to = 'my@email.com'; // user email TODO get user email based on $uid
    $language = language_default();
    $params = array(
        'username' => $user->name,
        'sitename' => variable_get('site_name', 'Drupal'),
    $from = variable_get('site_mail', 'default@email.com');
    $send = TRUE; // defaul = TRUE can be set to FALSE to not actually send the mail and only generate it.
    drupal_mail($module, $key, $to, $language, $params, $from, $send );
}

I've put a debug() in system.mail.inc above the implode function but that showed my message  $message['body'] was not an array ( $message['body'][] ) anymore.

Also when I put a debug on the result of the drupal_mail function I see that my subject is set but the body is empty.


texts: Show/hide entity registration form fields depending on registration state

texts:
I'm using the Entity Registration module on Drupal 7.

I want to show/hide custom fields on the registration form depending on the state of the registration. I thought to use the Conditional Field module to solve this, but in the Manage Dependencies tab only my custom fields show up: the state field can't be selected as Dependee.

Why is this and
How to get around it?


texts: How do you resize a form element in a block?

texts:
I have two blocks, one with a search forum(using drupal finder module) and an email invite module, and for some reason both input forms go outside the blocks borders.

Both are giving me two different problems.  The finder module's search bar is going beyond the block borders but the entire email invite block is outside the borders.

How do you adjust the size of blocks?


texts:
I am having a problem with saving values of a textfield in the database.

Usecase:
Users with a certain role should add two things on their accountpage the first time they login.
1.change their password
2.agree with terms.

Point 2 is the trouble part.
I have a text field with two values:
'Agree' and 'Not agree'
Now i like to hide the second option but with my current code the value of the agree option is not getting saved to the database.

Help appreciated
Thanks

Used code

<?php
function regform_form_user_profile_form_alter(&$form, $form_state,  $form_id) {
  global $user;
 // Making password required when role=In between role.
if( ($form_id == 'user_profile_form') and (isset($form['account']['pass'])) and (in_array('In between role', array_values($user->roles))) ){
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#required'] = TRUE;
    $form['account']['pass']['#type'] = 'password_confirm';
    $form['account']['pass']['#required'] = TRUE;

   // Disabling and hiding 'Dont agree field' field

  $form['field_agree'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
   'Agree' => t('Agree'),
   'Do not agree' => t('Do not agree'),

 ),
);
hide($form['field_agree']['Do not agree']);
 }
}
?>


texts:
I have written a simple module for counting node views. For each nid I store 2 numbers: impression and view.

1 Impression is when the node is loaded and visualized in any display mode (teaser, views ecc..) so when I open a taxonomy term page, every nid listed gets a +1 Impression. Or, for example, I have a view that loads some nodes displaing only its main_image fields: i want a +1 impression for every one of these.

1 view is when the node is viewed in full mode, so when is opened /node/12, nid 12 gets a +1 view.

This behavior is made simply in my module counter:

// hook for impressions
function counter_node_load($nodes, $types) {
    foreach ($nodes as $node) {
        // store in db +1 impression for $node->nid
    }
}

// hook for views
function counter_node_view($node, $view_mode, $langcode) {
    if ($view_mode == 'full') {
        // store in db +1 view for $node->nid
    }
}

that's it.

It will be awsome if this works with drupal cache enabled, but it doesn't. Probably because drupal cache stores the html of the page/block and the node_load, node_view isn't called anymore.
What can I do to achieve the same result explained above (impressions, views) with cache enabled?


texts: Drupal Commerce: How to manage different payments (a total amount can be pay in different shares and the user can choose in how many shares)

texts:
I´ve just installed the Drupal Commerce module in D7, and after watching the video tutorials I think it´s fairly complex, maybe it´s just too much for what I want to do.

I´ve this site where we only sell e-courses. Each course has a total cost, but people can pay just a small part to get enrolled.
The problem is that people have a minimum to pay, but they can pay a bit more if they want, so even is the total price is fixed, I get people to pay different amounts of money each time.

In example:

Course A costs 1000.

To get enrolled you have to pay 100, and then 100 per month (those are recurring payments).

Now, one student can pay 200 when he enrolls, and then after that he can, if he wants, to pay in 200 shares instead of 100 shares. Maybe he can pay 300 to get enrolled and then shares of 100 each.

How may I manage that with Drupal Commerce? Is it possible?

Thanks!


texts: How to limit users to a create only one instance of a node type?

texts: I know there is Node Limit module, but since it is in alpha stage since a rather long time, I am wondering if there is more elegant way to do so which does not need additional modules?


texts: Trying to update node using node_save() produces integrity constraint exception

texts:
This is the first time I've tried to do this so I may be missing something really obvious. I'm developing a module which uses hook_node_insert() to catch the creation of a node, and puts the node into Drupal Queue for later treatment by a cron process.

At the end of the process, I want to update a field in the node and save it. I've tried using entity_metadata_wrapper as well as node_save, but in both cases I get an error "PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3011' for key 'PRIMARY': INSERT INTO {node}....". Apparently, Drupal is unaware that the node exists already despite the fact that $node->nid is set (which is why we get a duplicate entry integrity constraint).

Looking at the node_save() code, it certainly seems to be supposed to check and load the node first if the nid is set (which it is - I've followed this step by step in debug). I must be doing something wrong, but what?

Here is the code from hook_node_insert which queues the node for treatment:

if ($node->type == "sms_message") {
  $queue = DrupalQueue::get('sms_message');
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $node_wrapper->field_queued->set(1);
  drupal_set_message($node_wrapper->label() . ' has been queued');
  $queue->createItem($node);
}

And here is the relevant code from the callback module for hook_cron_queue_info

function sms_textlocal_outgoing($node) {
  global $user;
  $user = user_load(1);
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $message = $node_wrapper->field_sms->value();
  $sms_sent = 0;
// Then we do some processing...
  $node_wrapper->field_sms_sent->set($sms_sent);
  node_save($node);

I've also tried:

$node_wrapper->save();

instead of node_save, but with the same result.


texts:
I tried some variations on the code below, but I have not been able to pass my custom form options to render().

class CustomField extends FieldPluginBase {

  public function query() {
    // This is a custom field.
    // Leave empty to avoid a query on this field.
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['my_options'] = [
      '1' => 1,
      '2' => 2,
      '3' => 3,
    ];
    return $options;
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {

    //Form select element.
    $form['my_options'] = [
      '#type' => 'select',
      '#required' => TRUE,
      '#title' => $this->t('My Options'),
      '#options' => $this->options['my_options'],
      '#description' => $this->t('Description.'),
      '#default_value' => 1,
    ];
    parent::buildOptionsForm($form, $form_state);
  }

  public function render(ResultRow $values) {
    return kpr($this->options['my_options']);
  }

}

As is the ['my_options'] key is empty. If I create the $options['my_options'] in buildOptionsForm() it does populate the select list in the views field form. Both, however, break the output of the render(ResultRow $values) function. No errors, just no output.

How do you create and pass options from defineOptions() to buildOptionsForm(), and inevitably access them in render(ResultRow $values)?

Trying to reference:
FieldPluginBase::defineOptions and Field::buildOptionsForm without success. As well as referencing: https://www.webomelette.com/creating-custom-views-field-drupal-8


texts: How to list all the commands in Drush 9 (aka: drush help)?

texts:
I'm trying to list all the available commands by drush help, however I've the error:

$ drush help
  [Symfony\Component\Console\Exception\CommandNotFoundException]
  Command  was not found. Pass --root or a @siteAlias in order to run Drupal-specific commands.

It was working in Drush 8, what's the equivalent command in Drush 9?


texts:
I am using Print module to print a Drupal node.
Recently users have asked the ability to print a node in form of individual pages.

For example if a paged 'Drupal' article spans on 5 pages, user wants the ability to print only 2nd page.

I tried to analyze the var_dump of a node (by pro-grammatically loading it) to find any information related to paging but I did not have any luck.

I am thinking to do paging of a node pro-grammatically and load different paged content in an array.

How can I do this ?

Please let me know if I need to provide more information.


texts:
I am working in Drupal and Magento Integration

Whenever i try to get session data using this code

require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
  umask(0);
  Mage::app("default");

  $session = Mage::getSingleton("customer/session");

  if ($session->isLoggedIn()) {
    $block['content'] .= $session->getCustomer()->getName();
    #var_dump($session->getData());
  }
  else {
    $block['content'] = t('User not logged in');
  }

it fails to fetch the data.

But when i run this from independent php code it works fine.

But magento's catalog objects are running perfectly inside Drupal

What could be the problem. Any suggestions

Am using D7

EDIT

require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
      umask(0);
      Mage::app();
      Mage::app()->getTranslator()->init('frontend');
      Mage::getSingleton('core/session', array('name' => 'frontend'));

      // switch off error reporting
      error_reporting(E_ALL & ~ E_NOTICE);

      // Brands category => ID = 101
      $brand = Mage::getModel('catalog/category')->load('4');
      $brands = $brand->getChildrenCategories();

      foreach ($brands as $node) {
        $items[] = array(
            'data' => t($node['name'])
        );
      }

      $block['content'] .= theme('item_list', array(
          'items' => $items
              ));

This is the code i use to get the catalog products from magento and display in drupal
I don't use any package for that.This is working perfectly.


texts: How to make downloads available to approved download requests?

texts:
The idea here is any registered user can attach a file to a certain node. However, users have to request for download access from the node author to be able to get the file.

I've searched for file access related modules and so far, they are all role-based. My need is per-author && per-requestor && per-node based.

Is there an existing module for this? Or is there another way to achieve this by linking certain modules together? Connect the dots?


texts: How do I get a date selector field in a content entity?

texts:
I have a content entity in Drupal 8 that generates form for datetime. I just want to show only the date selector in the form, but it shows date and time selectors.

     $fields['start_date'] = BaseFieldDefinition::create('datetime')
            ->setLabel(t('Start date'))
            ->setDescription(t('The date that the survey is started.'))
            ->setRequired(true)
            ->setDisplayOptions('view', array(
                'label' => 'above',
                'type' => 'string',
                'weight' => -4,
            ))
            ->setDisplayOptions('form', array(
                'type' => 'date',
                'weight' => -4,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);

How do I show only the date selector?


texts: Display Content with Taxonomy on User and content matching with Multiple Vocabularies

texts:
I am trying to create a view to show content that is tagged with taxonomy terms from the users profile (each vocabulary has its own field in the users profile where the user can select via check boxes what they are interested in.)

I read and watched multiple tutorials and articles on this, and the closest I can get is described here by Triskelion:

  create a user view, add relationships: Content: Tags (my Vocab) and Taxonomy term: Content with term with a contextual filter on the User:UID, then display the content:title. This works perfectly given one vocabulary, but I cannot for the life of me get it to work correctly with multiple vocabs.

I added multiples of the above relationships for each of the vocabs, and display multiple content:titles with each relationship, but the problem is that each row in the view will contain only one different title. Aggregation and Querey distinct settings don't seem to help!!

Can anyone point me in the right direction. I know there is a solution to scrap my multiple vocabularies and just put all terms into one but this is not really desirable, as id lose the structure of my taxonomy.


texts:
According this bug issue,
hook_file_download is called twice when private style image is requested. The first time is requested original image without style and then the style image is called. Is there any workaround to skip checking access of original image?

In particular, I have a website, where user can share his private images on his facebook account. Then I need to allow facebook to send http request to download image. The problem is, that facebook hs limitations on size of images. Facebook doeasn't accept larger images when downloading thumbnails from my website. As I tested it, although my image thumbnails are small, drupal system check access against large original image so facebook doesn't accept the thumbnail.

Is there any workaround, how could I solve this problem?

thanks for advice
Tomas


texts: Call another view with a single exposed filter

texts:
I have a page view which works fine for two cases in the exposed filter (say school one and school two).

However, if school three is chosen in the exposed filter, I want another view to be displayed instead of the page view for school one and school two.

I don't mind if it's a block view or page. Just to call another view because its display is different (a summary of school one and two in addition to school three)

@No Sssweat


texts: Colorbox not working in new content type

texts:
I have Colorbox and the plugin installed, and enabled.

The module is in the sites/all/modules folder, and the plugin is in the sites/all/libraries folder.

I've created a new content type and called it Image Gallery.

I've created a new field for that content type also called Image Gallery

The display format for my Image Gallery field is set to Colorbox.

I can create an image gallery, but the images are not opening in Colorbox. I'm stuck, the console isn't showing any errors, as far as I know everything is configured right but it's not displaying properly. What am I missing?


texts: how to insert image inside an existing image

texts:
hi i'm working on my sample site.in that I've done the background image blue sky into the respective region how can i add one more image in center of that like below ? and more over
I've to add an web form in that center image i'm going to add? how can i achieve this?


texts:
By default, it just available to flag or unflag an item, reference here. I want to add a link to unflag all flagged node of current user, is there any way to do that?

At this moment, I get the code to clean all flagged node, but I don't know how to make this snippet as a link

db_query("DELETE FROM {flag_content} WHERE sid = %d", flag_get_sid());


texts: How to pass metatags from a node into a view?

texts:
I'm sending the information of my node into an external application and I need to be able to send the meta tags of that node as well. Unfortunately, I do not see the meta tag fields.

My question is...

How can I send my meta tags into a view?

NOTE: I'm using the Metatag module, I have seen few posts that suggest using the metatags_quick module to add this functionality. However, I need to be able to do it with the instead Metatag module


texts: How can i modify the height of input textfield in login form in drupal 7?

texts:
how can i costumize a form ( for example login form ) in /user and specifically the height of input textfield? And the button "login"?
I try with the function theme_form_element() but nothing good!


texts: Turning a query string into an array after using parse_url

texts:
Okay, I am afraid this might be a 'duh!' question, but I am just having one of those days!   Well, the problem is, I am getting the following error every time I have a query string in my url (https://www.google.com/?q=hello):

Recoverable fatal error: Argument 1 passed to drupal_http_build_query() must be an array, string given

I am modifying a custom module that someone else wrote and this is the code that is problematic.

$pieces = parse_url($href);
$pieces['html'] = TRUE;
$pieces['path'] = isset($pieces['path']) ? $pieces['path'] : '';
if (isset($pieces['scheme'])) {
  $pieces['path'] = $pieces['scheme'] . '://' . $pieces['host'] . $pieces['path'];
}

return l($image, $pieces['path'], $pieces);

This is what $pieces looks like:

scheme (String, 5 characters ) https
host (String, 13 characters ) www.google.com
path (String, 22 characters ) https://www.google.com/
query (String, 6 characters ) q=hello
html (Boolean) TRUE

Obviously, the problem is due to $query not being an array.  I am wondering how best to rewrite the above code so that I can properly call the l() function with the query string and any other attributes that a user might put in there.  Any and all help would be greatly appreciated.  Thanks.


texts: Drupal 7 site login works on XAMP localhost windows 7, but login doesn't work on UNIX

texts:
The problem that I'm having is that of the LOGIN functioning on my site.  On my laptop, localhost, the site works fine and logins work with no problem.  When I port the site over to our UNIX server, the site works fine EXCEPT I cannot login.  None of the logins work.

I've tested the DB, by using the DB on UNIX instead of localhost, and again, no problems.

I've Googled this issue and none of the suggestions have worked, i.e. make sure rewrite_mod is on, change permissions, etc.

Has anyone encountered this issue?  If so, how were you able to resolve it?

Again, its strange because there are NO problems with the site on my localhost, but the login doesn't do anything on UNIX, the login screen just reloads.

Thanks,

KP


texts:
I have a view object and I'd like to get the contextual filters that were passed to it.

I have this tidbit of code that prints out the arguments field name.

if (!empty($view->argument)) {
  foreach ($view->argument as $id => $arg) {
    print $arg->field;
  }
}

I'm trying to get the values of those fields.


texts: How to configure the toolbar in CKEditor?

texts:
I've installed CKEditor in my drupal instance and all seems to work well until I realized, I can't change the text size (missing drop down). I went to admin/config/content/ckeditor and selected and saved Toolbar full from the examples, which feature a Size dropdown as shows in the "current toolbar' preview. I did this for both existing profiles, Advanced and Full. However, if I then go to admin/structure/block/add to add a new block, CKEditor still does not show a size drop down so that I could change the text size. Why not, what am I missing?

EDIT 1

I went to http://ckeditor.com/download and downloaded the full package which I then just copied to my existing sites/all/modules/ckeditor/ckeditor overwriting the existing standard package copy. I've reset the cache`, however what I'm seeing now is this:

The Size drop-down is visible but other buttons have failed to load their icons.

Any suggestions?


texts:
I am using computed field module in a Drupal 8 installation. I set up a prototype project on a Raspberry Pi, where computed field module runs like desired. Now I set up a fresh installation on a shared server, installed the exactly same version of computed field and Drupal on it. In this installation, computed field misses the "Formatter"-dropdown-field in the view field settings.

Instead, I can only choose "default" and "unformatted". Does someone maybe know why this could be? Different permissions on the server maybe? As said, it's two times the same versions installed.


texts: How to determine the modules enabled on a third party website?

texts:
When I don't have the admin access to a site, how can I find out the modules that are enabled on the site.

For example : How can I identify various modules enabled on www.drupal.org


texts:
So i know how to order fields when creating/editing a content type. But say i have three fields in a content type:

name
last name
nick

and want these to be draggable when a user creates a new node.

Any suggestions?

Thx!


texts: How do I change the javascript loading order

texts: I am using mixitup.js for my custom module. But it gives error when firing because it needs to load the jQuery before loading the mixitup.js. But my jQuery files are in my site folder which are loading in the end of the page. Is there way to load my mixitup.js in the end of the page. mixitup.js should be in my custom module too.


texts:
I'm a little new.
I need to create a view for related content between different content types, some have same taxonomies field other no. It is a multi language site. So, the view was a little complex, then I am trying with EntityQuery. This search needs to be updated each time that the user update a taxonomy

How can I present the result of my entity query in a node? in a custom block? where can I put my code ?

I asking for a structure or a way to do it this.


texts: language variable is empty for custom module

texts:
The languagevariable is added to the twig variables by default but it is empty for my custom module which is rendering a page.

I tried adding theme_preprocess_page hook inside the *.module file but the variable is already set there...

Do I have to add it manually through the routes file or is there any alternative?


texts: How to correctly add Google AMP .js files to my theme

texts:
I'm using the Drupal AMP module,theme and library in Drupal 7

I'm using the AMP verification tool here validator.ampproject.org

I have the amp-sidebar working fine except the JavaScript causes an error.
When adding the AMP internal js file I get the below error when validating.

<script async custom-element="amp-sidebar" src="https://cdn.ampproject.org/v0/amp-sidebar-0.1.js"></script>

I get the following warning

"The tag 'script' is disallowed except in specific forms."

The second error i get is the following.
And as a result of that I get this error
  The tag 'amp-sidebar extension .js script' is missing or incorrect, but required by 'amp-sidebar'. Learn more.

I have included the full HTML file contents below if you want to run it through the validator to see the errors live, Just copy and paste the code.
Pastebin of full Drupal AMP page


texts:
I'm no newbie to using Drush, but I'm working on a "legacy" install that I have a feeling hasn't been set up right.

This is the relevant (my purposes) part of the drush output. I can see the commands I'm trying to work with listed.

  SQL commands: (sql) sql-cli (sqlc)        Open a SQL command-line
  interface using Drupal's    credentials.             sql-connect
  A string for connecting to the DB.
  sql-create            Create a database.
  sql-drop              Drop all tables in a given database.
  sql-dump              Exports the Drupal DB as SQL using mysqldump or
  equivalent.               sql-query (sqlq)      Execute a query
  against the site database.                                sql-sync
  Copy and import source database to target database. Transfers via
  rsync.

The only commands that work are sql-cli and sql-dump, though.

This is the output from running drush sql-load --help.

  The drush command 'sql-load' could not be found.  Run drush
  cache-clear drush to clear the commandfile cache if you have
  installed new extensions.

For reference I'm using drush 5.7.  And yes, I have run drush cc drush to no avail.

I'm leaning towards gutting out this version of drush and starting from scratch, as it was not built system-wide and I had to add a custom PATH variable in order to find drush, but if anyone has any insight I would love to hear it.

EDIT: Providing more information for everyone.  The OS is Ubuntu 12.04, fairly standard Apache2 with Amazon RDS dbs.  The sad thing is, I have no reference for how it was initially installed.  which drush outputs /usr/bin/drush but it also exists in /var/www/<webroot>/bin/drush, which is the version I've been using and that is causing issues.  My standard MO is to install drush as an Ubuntu package, and I've never had any issues that way.


texts: Custom widget field only saves first letter, disappears on edit

texts:
I'm trying to create a custom module for Drupal 7 that makes two widgets available for Text fields. They autocomplete from a database table using #autocomplete_path. The autocomplete works fine and when a match is selected it is made the value for the field, but when the node is saved only the first letter from that field is shown. Then when the node is edited, the field comes up blank in the edit form.

Here's my module code:

<?php
/**
 * Implements hook_menu().
 */
function autocomplete_jsb_users_menu() {
    $items['jsbu/speaker/autocomplete'] = array(
        'page callback' => 'jsbu_speaker_autocomplete',
        'access callback' => TRUE,
        'weight' => 1,
    );
    $items['jsbu/venue/autocomplete'] = array(
        'page callback' => 'jsbu_venue_autocomplete',
        'access callback' => TRUE,
        'weight' => 2,
    );
    return $items;
}

/**
 * Implements hook_field_widget_info().
 *
 * Two widgets are provided.
 * - A textfield Speaker name autocomplete widget.
 * - A textfield Venue name autocomplete widget.
 */
function autocomplete_jsb_users_field_widget_info() {
    return array(
        'autocomplete_speaker_name' => array(
            'label' => t('Autocomplete Speaker Name'),
            'field types' => array('text'),
        ),
        'autocomplete_venue_name' => array(
            'label' => t('Autocomplete Venue Name'),
            'field types' => array('text'),
        ),
    );
}

/**
 * Implements hook_field_widget_form().
 */
function autocomplete_jsb_users_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    // set the default text instance
    $element += array(
        '#type' => 'textfield',
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => $field['settings']['max_length'],
        '#attributes' => array('class' => array('text-full')),
    );

    if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
        $element['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
    } else if($instance['widget']['type'] == 'autocomplete_venue_name') {
        $element['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }

    return $element;
}

/**
 * Implements the autocomplete_jsbu_speaker() callback.
 */
function jsbu_speaker_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_speaker_name', 'sn');

    // Select rows that match the string
    $query
        ->fields('sn', array('field_speaker_name_value'))
        ->orderBy('field_speaker_name_value', 'DESC')
        ->distinct();

    $result = $query->execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_speaker_name_value] = check_plain($row->field_speaker_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

/**
 * Implements the autocomplete_jsbu_venue() callback.
 */
function jsbu_venue_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_venue_name', 'vn');

    // Select rows that match the string
    $query
        ->fields('vn', array('field_venue_name_value'))
        ->orderBy('field_venue_name_value', 'DESC')
        ->distinct();

    $result = $query->execute();

    // add matches to $matches
    foreach ($result as $row) {
        $matches[$row->field_venue_name_value] = check_plain($row->field_venue_name_value);
    }

    // return for JS
    drupal_json_output($matches);
}

Any ideas? Thanks!


texts: I have configurations on store>configuration>completion messages. But they are not reflecting on the site. For example I have set the checkout page as a node I created but it's still using the default checkout page. I have cleared all the cache. What am I missing?


texts: Facet Blocks are not appearing in indexed views

texts:
I have created Index with apache solr server using search API.

Created a view using that index in page display and facets are appearing as rendered in side bar.

Now I Created another block display in the same view but now the facets are not displaying in the block display.

What would be the problem with block display and facets?


texts: how to hook checkout pane defined in another module?

texts:
I try to make a small change to Drupal Commerce Coupon pane (add a div to it). I tried to hook this function:

    function commerce_coupon_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
              // Allow to replace pane content with ajax calls.
              $pane_form = array(
                '#prefix' => '
',
                '#suffix' => '
',
              );
        (..)
}

To do this I created a function in my module:

function <mymodule>_form_commerce_coupon_pane_alter(&$form, &$form_state, $form_id) {
        $form['#prefix'] = '

You have coupon? Add it here.
' + $form['#prefix'];
        $form['#suffix'] = $form['#suffix'] + '
';
    }

but it do not work. I think that there should be other way to hook checkout pane but I cannot figure out how to do this.


texts:
I would like to create a settings page for a user which allows them to save the options of a list which is to be used in a custom form. The list is called marketing source and it is added to a form which gets submitted with plain text values to an external API.

I know in field config for select lists you can do this but I want to do it on a custom config page for that specific list.

Foe example I would have a textfield in the config that had values like this

1|google
2|magazine

Then I need to convert that into a seralised array and store with variable set.

Is there a function that does that already for the field form?

Cheers Dan


texts: Adding Search Block to Bootstrap 3 Navbar

texts:
The search block using the twitter bootstrap 3 theme doesn't show inline with the rest of the navbar. What is the trick to get this to show inline?

I have tried to add it to the page.tpl.php without success.

Any ideas?

EDIT:::

I've added this to the template:

           <?php if (!empty($page['searchblock'])): ?>
            <?php print render($page['searchblock']); ?>
          <?php endif; ?>

However, that doesn't seem exactly right for this bootstrap theme. In the bootstrap code one wraps the search like so:

<form class="navbar-form navbar-right" role="search">

    <input type="text" class="form-control" placeholder="Search">

  <button type="submit" class="btn btn-default">Submit</button>
</form>

Do I need to modify the default search block template? Thanks for any help to my ignorance as i learn this system. Really digging Drupal 7 right now!


texts:
I am trying to use the fade in effect in Drupal when I load a page.

In my Omega sub-theme I have included the following line in its .info file.

scripts[] = '/js/custom.js'

In the script, I have included the following code.

$(document).ready(function() {

$("body").css("display", "none");
$("body").fadeIn(2000);

});

If I load the page, I see no effect at all, but I clearly see that my JavaScript is in the header.

<script type="text/javascript" src="http://localhost/innodru/sites/all/themes/CHILDTHEME/js/custom.js?m2zpiw"></script>

I have cleaned the cache and tried a lot of things, but it does not look like is working.
I am using Drupal 7.


texts: Display the method of payment of an order on the invoice pdf comerce billy

texts:
I installed Commerce Billy.

How can I display the payment method on my bill?

<?php

/**
 * @file
 * Template for invoiced orders.
 */

?>
<?php
//The code to get payment type

$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}
?>

    <img src="<?php print $content['invoice_logo']['#value']; ?>"/>

<?php print render($content['invoice_header']); ?>

<?php print render($content['commerce_customer_billing']); ?>

<?php print render($content['commerce_customer_shipping']); ?>

<?php print render($content['invoice_title']); ?>

<?php print render($content['invoice_header_date']); ?>

<?php print render($content['order_id']); ?>

  <?php print($payment_method); // Use this PHP Code where you want to print the payment type, you can style it any way, adding div, span, whatever you want ?>

<?php print render($content['commerce_line_items']); ?>

<?php print render($content['commerce_order_total']); ?>

<?php print render($content['invoice_text']); ?>

<?php print render($content['invoice_footer']); ?>

Here are the contents of my file "commerce_order--commerce_order--pdf.tpl.php".
Where do I put the code ?


texts:
I have enabled the "User Login" block inside the Content Region and configured it to show on two specific Views which should be password protected.

I have also created two Views and two different access roles for each view.

After I access the password protected pages as anonymous user, I can see both Login screens  and authentication on one page works but refreshing the second page shows:

Access denied
You are not authorized to access this page.

Also if I authenticate on page A with login for page B, I get the same message but refreshing page B shows the content.

Could this be a cookie related issue, because I have to clear my browser cookie to logout. Does Drupal only allow one login cookie?


texts: Adding hundreds of fields to a content type in Drupal 6

texts:
I have over a hundred fields to be added.

How can I use CSV or SQL statement to add these fields in Drupal? Is there any module to do this?


texts: Role cannot be used to create content without having administer permissions

texts:
I am using Organic Groups on a Drupal 7 website. I created a Group content type and a few user roles.
I want to make sure that a user role can create and edit the Group content, but not delete it. I enabled all necessary permissions, but I get an internal server error when trying to create the content.
However, when I add the Administer Organic Groups permissions permission to the role, users with that role can create content. An unwanted side-effect is that the role can also delete content.
How can a role be allowed to create Organic Groups content without having the permission to delete it?


texts: Compromised D7 Sites due to SQL Injection Security Bug "Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003"

texts:
I have few websites running Drupal 7 and i upgraded them all on 16th October 2014.

Since 3 days we are monitoring the websites and we haven't seen any problem or evidence of our system being compromised.

I am wondering if there is anyway to identify if a Drupal 7 sites has been compromised?

It will be really helpful if we all post our views, any evidence of system being compromised and any action that could be helpful to make sure we are secure.


texts:
I have an AJAX form that I've created into a block exposed on my current page. I will have an interface that will allow the users to select an indefinite amount of content to be used within the submit function of the form.

All the variables that will be passed to my form are node ID numbers, but there could be 1, there could be 50.

I have the Jquery action ready to update my ID numbers but I don't know how to get my ID number from Jquery into a variable, which can then be read when the AJAX form is submitted.

I've been looking at this - How to pass Javascript variable with form on submit?

and this - How to trigger a form and pass variables to $form_state with jQuery?

And I've been looking at the responses to both, but neither seem to give me access to the data I need, or are only speaking about a single variable, I need to pass a list or an array.

Would it be best to write something to trigger the form rebuild when I provide a new ID and allow the ID to be written into the form via that method?


texts: How to let views's sort criteria random equally

texts:
I have two node content. I want to know which content is able to convince user to sign up.

I create a views block and two node contents. The views will randomly choose one node content and display.

At the views sort criteria, I choose global random, but it does not random equally. It choose option A more than option B.

Question: How to let it choose random equally or alternate such as A,B,A,B,A,B..etc?


texts: Importing nodes from custom XML feed: how do I convert some XML fields into entity references?

texts:
Here's the problem:

I'm migrating a Wordpress website to Drupal. It's a gaming portal with a highly customized Wordpress with custom fields, so we decided to generate some XML dumps from Wordpress, then use Feeds module to import that. There are two different "content types", games and articles about those games (strategy guides, tricks, so on). We have two content types, so we generate two XML files. All good so far.

The problem is that those two content types are related. To be precise, the "article" content type is always referred to a game. In Drupal terms, "article" contains an entity reference fields that points to a node of type "game".

Where's the problem?
Example: we have an article entitled: "8 tricks for Clash of Clans". This article refers to game "Clash of Clans". The problem is: in our XML we have "Clash of Clans", written in words. I want Feeds module to those words to Node IDs, then save those Node IDs as node references.

I want to do the same with some Taxonomy Terms.

Makes sense?


texts: Allow creation of new content type just like taxonomy

texts:
I like the way the Taxonomy module allows users to create a new taxonomy term "on-the-fly." Are there any modules that can also allow users to create new "content" of a node "on-the-fly"? Here is my scenario:

Content Type A (Companies)
Content Type B (Users)

Users have node reference to Companies, so every time a new user is added, a company is selected for this user.

I need to be able to just add a user directly on a Drupal 6 site, and if a company does not exist, I can also add a new company right there on the same page while adding that user. This works very similary with taxonomy, but I don't want to reference a taxonomy since Content Type A has also a lot of fields attached to it, which a taxonomy cannot do.


texts: Leaflet appears as Grey Box and Zoom not working

texts:
I am using geofield and leaflet.widget in a content type field. I have a leaflet view containing nodes with these field locations.

Upon displaying the view at first a grey box appears in place of the leafletmap. One click of the zoom (plus or minus) triggers the appearance of the map. But thereafter the zoom then does not work. Clicking plus or minus does nothing. This is happening both to the display of leaflet fields in rendered nodes and to the leaflet view.

Setting the Initial Zoom Level to 13 will at least allow the map to appear. But this only works on views with one vectored location and not on views with many vectored locations.

I have tried using both ESRI World Street Map and Google Road Map.


texts: how to render create page form & list of contents in page.tpl.php

texts:
I am theming an admin page & I require to load/render admin forms in page.tpl.php file. The final output should be somehow like the attached screenshot. Scroll below to see screenshot & code written in page.tpl.php.

Admin Page

  <?php print drupal_render(drupal_get_form('node_admin_content')); ?>

  <?php print drupal_render(drupal_get_form('page_node_form')); ?>

I was searching for this solution & I came across this "print drupal_render()". Please suggest best solution for this. I have render same kind of pages in other tpl.php files.


texts: Add icon to module's menu item in Administration menu

texts:
I've searched for a bit and I haven't found a solution to my liking: I want to avoid adding more modules to the project.

I'm very new to Drupal, so I have minimal knowledge on that matter. I have this project which somebody else has made. They created a module which adds a menu item on the Administration menu. What this module doesn't do, is add an icon to the menu item, which makes it look bare.

I want to add a custom icon I've made next to the menu item text. The reason it needs to be a custom icon and can't be fontawesome (or anything of its liking), is because it has to be a variation of the site logo.

Is there a way to accomplish this without adding more modules to the project, or is adding more modules the only way?

It's Drupal 8 with Lightning on Debian 9 with Apache2.4 and PHP7.2.


texts:
I am trying to validate the form. I have one hidden textbox and one check box group.

field_institute_event - represents checkbox group.
posted_student_list - represents hidden text box.

If both are empty then I want to display error message. How to do that??

I am trying following code:

if((empty($form_state['values']['field_institute_event']['und'][0]['entity']->field_institute_event_group[LANGUAGE_NONE]))
        &&
        (empty($form_state['values']['posted_student_list']['und'][0]['entity']->field_institute_event_group[LANGUAGE_NONE])) ) {
  form_set_error('field_institute_event_group',t('Please Post to atleast one group'));
}


texts: How can I accurately determine when a customer is on the "Review" step in Commerce?

texts:
I've created a custom checkout pane by extending Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase and added it to the "Order information" step in a checkout flow.  This accepts customer data.

The customer then progresses to the "Review" stage to confirm everything is correct. The customer can "Edit" their information if required, going back to the "Order information" step.

Within the custom pane I'm wanting to determine whether it's being displayed in the "Order information" step or the "Review" step.

getStepId() always returns what's in the config for the pane. In this case, "Order information".

$this->order->checkout_step seems to always return "Review", or maybe it's just reporting the highest step reached in the order thus far.

Is there a Commerce native way of determining the exact step being viewed? Or will I need to check the URL directly?

Edit: I've tried checking the route name, but both /checkout/[id]/order_information and /checkout/[id]/review return commerce_checkout.form.


texts: How is a variable passed to theme_hook (theme_item_list, FacetAPI)

texts:
Problem

I'm trying to register a new theme function based off theme_item_list to alter the display of a facet.

Theme_item_list is passed in an array $variables. Crucially I can't work out how the facetAPI passes the variables needed for theme_item_list to render a list. It sets up the array in the execute method of FacetapiWidgetLinks and somehow successfully passes this to theme_item_list but I can't get my own theme function to receive anything.

How does theme_item_list receive it's $variables array?

More Information

Code altered thanks to kiamlaluno

I currently have the following code in my module:

function my_module_theme($variables) {
  return array(
    'item_list_aggregate' => array('variables' => array(
      'items' => array(),
      'attributes' => array(),
      'title' => NULL,
      'type' => 'ul',
  )));
}

//this is correctly called but $variables is empty
function theme_item_list_aggregate($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  ...

#items and #attributes values are set in the execute method below.

They are correctly passed to theme_item_list because I can't get them to pass to my theme function, theme_item_list_aggregate, the $variables variable in my_module_theme is empty.

class FacetapiWidgetLinks extends FacetapiWidget {

...

public function execute() {
    $element = &$this->build[$this->facet['field alias']];
    $this->setThemeHooks($element);

    // Here I call my own theme function. It's identical
    // to theme_item_list at the moment but my own theme function
    // never gets passed the $element array.
    if(strpos($this->facet['field alias'],"aggregation") != FALSE) {
      $element = array(
        '#theme' => 'item_list_aggregate',
        '#items' => $this->buildListItems($element),
        '#attributes' => $this->build['#attributes'],
      );
    } else {
      $element = array(
        '#theme' => 'item_list',
        '#items' => $this->buildListItems($element),
        '#attributes' => $this->build['#attributes'],
      );
    }
  }

...


texts: Date time formats: October not correctly written in German

texts:
I created a time format in Drupal administration (admin/config/regional/date-time) with the following settings in EN/ DE:

DE: d. F Y -> 05. October 2016
EN: dS F Y -> 05th October 2016

The problem is that "October" is written in German like "Oktober" ("k" instead of "c"). The strange thing is that the translation works fine with every other month ("May" for example becomes "Mai" in German) but just the October is written wrong. This appears to be an issue no matter where the date field is rendered, in views or node detail page.

Additionally this seems to be an issue with the PHP date format as it the same problem when using date('d. F Y', $timestamp). Can anyone give me a hint how to solve this issue?


texts: I am doing a module in drupal 8, I would like to know how to execute a function automatically every month. I think it's done with Cron, but I only get to do it every week. as I edit it from my function.


texts: Is there any preprocess hook for date api?

texts:
As I asked in above, Is there any theme preprocess hook for all of the dates that displayed in Themes Files?
I want to perform some mathematical operations on Dates that show on any content type,
Is there any solution to achieve it in my Themes Files.


texts: Disable caching for a front page path processor

texts:
I’m working on a project where users can create a book (core functionality). In a simple text field they can connect a domain to this book. This way the book is only accessible via this domain.
For example I have Book A with path node\1 and with domain a.book.com. I also have Book B with path node\2 and connected to domain b.book.com.
What I want now is if a visitor goes to a.book.com the frontpage is node/1. And if they go to b.book.com the frontpage should be node/2? I created a custom module for this book_frontpage.
For this I used large parts of the PathProcessorFront.php from core.
The code of my book_front.services.yml is:
services:
  book_frontpage.path_processor_front:
    class: Drupal\book_frontpage\PathProcessor\FrontPagePathProcessor
    tags:
      - { name: path_processor_inbound, priority: 300 }

The code of my FrontPagePathProcessor.php is:
<?php

namespace Drupal\book_frontpage\PathProcessor;

use Drupal\Core\Database\Database;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Path processor to replace 'node' with 'content' in URLs.
 */
class FrontPagePathProcessor implements InboundPathProcessorInterface{
  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request)
  {
    if ($path === '/') {
      //current domain
      $currentDomain = $_SERVER['SERVER_NAME'];

      //get nid of reader where domain is set
      $nid = Database::getConnection()->select('node__field_domain', 'd')
        ->fields('d', ['entity_id'])
        ->condition('field_domain_value', $currentDomain, '=')
        ->execute()
        ->fetchField();

      //get path
      $path = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid);

      if (empty($path)) {
        // We have to return a valid path but / won't be routable and config
        // might be broken so stop execution.
        throw new NotFoundHttpException();
      }
      $components = parse_url($path);

      // Remove query string and fragment.
      $path = $components['path'];

      // Merge query parameters from front page configuration value
      // with URL query, so that actual URL takes precedence.
      if (!empty($components['query'])) {
        parse_str($components['query'], $parameters);
        array_replace($parameters, $request->query->all());
        $request->query->replace($parameters);
      }
    }

    return $path;
  }
}

Now when going to a.book.com I see node/1 but when I go to b.book.com I also see node/1.  When I clear cache and first go to b.book.com I get node/2 but when going to a.book.com I also get node/2. So this looks like a cache problem.
How can I disable caching of this front page path?


texts: How to change the content moderation state in a custom submit handler?

texts:
I am trying to change the content moderation state from draft to submitted programatically.  The Content Moderation module adds a field to content types with a dropdown to change the state, but I want to hide this field from users and instead show a custom submit handler that changes the form state.

I can change the default value of the moderation field with code like this:

  $form['moderation_state']['widget'][0]['state']['#default_value'] = "submitted";

But, how do I change the value for the content moderation field using $form_state in the submit handler?

  $form_state->setValue('moderation_state', 'submitted');`

does not work like it does for fields.

Here is the debug output for kint($form['moderation_state']['widget'][0]):


texts: user_save adds values to the user, but they aren't "active"

texts:
I'm taking over a website that had a user import; it has a function that sets the value for some Boolean fields on the user.

$user->field_perm_connexion['und'][0]['value'] = (int)$permissions['perm_connexion'];
user_save($user);

When I edit the user, the value is correctly checked; when I execute code like the following, the value is wrong.

$user_perm = user_load($uid);
// don't judge the ['und'][0]['value']
if(!empty($user_perm->field_perm_connexion) && $user_perm->field_perm_connexion['und'][0]['value'] == 1){
    $is_allowed = TRUE;
}

I need to go to the user page (in the people menu) and save again, to get the correct values.

What could the problem behind this be?


texts: How to update drupal (with composer) and not update to the latest major drupal release

texts:
not very familiar with composer yet

I run composer update on a dev version (thank GOD) but from 8.2.6 drupal was updated to 8.3.0 but some functionality was broken due to the upgrade ... how can I safely run composer update and not upgrade to latest drupal ... or is there some other command I should run instead ?

I understand that I probably have to change the composer.json to do it but I don't quite know what it is that it I need to include in it

Any help would be appeciated

this doc article don't quite explain such a thing

UPDATE

I run the command from eyal composer require drupal/drupal:8.2.* but creates problem and site was unusable after that (received 500 error)

giorgos@glaptop:~/websites/domain.com$ composer require drupal/drupal:8.2.*
./composer.json has been updated
No patches supplied.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/drupal (dev-8.2.x 2125663)  Cloning 2125663da0 from cache
Writing lock file
Generating autoload files

Installation failed, reverting ./composer.json to its original content.

  [RuntimeException]
  Could not scan for classes inside "docroot/core/lib/Drupal.php" which does not appear to be a file nor a folder

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] [<packages>]...

I had to run composer update and now with the 8.3.1 version of drupal the composer update run smoothly.  I just needed to run drush up rules-8.x-3.x-dev after that since there was a problem with rules and 8.3.1

EDIT
Anyone knows why my question received -2 ? (was I downvoted ? what is the reason ?)


texts: Drupal 7 Bartik plus theme drop down menu

texts:
This is actually, must be easy question, ive been fiddling around for some hours trying to figure it out.

The short version is I am making a drop down menu in Bartik,

I am aware of superfish,nicemenues,megamenues, But I am not interested in these.
Since Bartik runs with superfish built in.

I came across this Drupal 7 Bartik Plus Theme
with a fresh install of Drupal

But this menu isnt working. The default menu is not showing.

as you can see here this is how it supose to work

Drupal 7 Bartik Plus example

Any good ideas to how I get it to work?.


texts: Site errors out when trying to create a subtheme based on Classy

texts:
I'm creating a custom theme in Drupal 9 and am trying to use classy as my subtheme but get the following error:
The website encountered an unexpected error. Please try again later.

Drupal\Core\Theme\MissingThemeDependencyException: Base theme classy has not been installed. in Drupal\Core\Theme\ThemeInitialization->getActiveThemeByName() (line 122 of core\lib\Drupal\Core\Theme\ThemeInitialization.php).

Drupal\Core\Theme\ThemeInitialization->initTheme('custom_theme') (Line: 406)
Drupal\Core\Theme\ThemeManager->initTheme(Object) (Line: 96)
Drupal\Core\Theme\ThemeManager->getActiveTheme() (Line: 214)
Drupal\Core\Theme\Registry->init(NULL) (Line: 258)
Drupal\Core\Theme\Registry->getRuntime() (Line: 194)
Drupal\Core\Entity\EntityViewBuilder->getBuildDefaults(Object, 'full') (Line: 61)
Drupal\node\NodeViewBuilder->getBuildDefaults(Object, 'full') (Line: 157)
Drupal\Core\Entity\EntityViewBuilder->viewMultiple(Array, 'full', NULL) (Line: 123)
Drupal\Core\Entity\EntityViewBuilder->view(Object, 'full') (Line: 98)
Drupal\Core\Entity\Controller\EntityViewController->view(Object, 'full', NULL) (Line: 66)
Drupal\node\Controller\NodeViewController->view(Object, 'full', NULL)
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 573)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 158)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 80)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 705)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Below is my theme.info.yml info:
name: Custom Theme
type: theme
description: "This is a custom theme for the company"
version: "1.0.0"
core: 8.x
package: "Custom"
core_version_requirement: ^8 || ^9
base theme: classy

# libraries:
#   - custom_theme/bootstrap_cdn
#   - custom_theme/global-styling

regions:
  search: Hidden Search Bar
  branding_navigation: Branding & Main Navigation
  header: Header
  primary_menu: Primary menu
  secondary_menu: Secondary menu
  content: Content
  footer: Footer

Why is it saying that 'Base theme classy' isn't installed? I've never run into this issue before. Does it have something to do with Drupal 9? (This is my first time starting from scratch in D9)
I see that classy is in the core files so not sure why I'm getting this error?
Any help/suggestions?
EDIT: I'm using Acquia Dev Desktop if that makes any difference.


texts: How do I filter a view page with contextual filter?

texts:
I have an all events views page where I would like to put the links 'All Events', 'Upcoming Events', 'Past Events' in the header.

I would like to link them to the same views page but show filtered results. It seems possible by looking at contextual filters but not sure which way to go.

Thanks,


texts: How to disable cache for a specific content type?

texts:
I use Drupal 8 and I want to disable caching for a specific content type in full view mode.

I've found how to disable caching for all view modes, but I want to disable it for only a specific content type.

How can I do that?


texts:
I have to develop a monthly online magazine and I am looking for suggestions on the best way to organize the content.

Since it's a monthly publication, I want to organise content under January, for example. January will have multiple articles, advertisements etc all of which are nodes.

When time moves on to February, I want to unpublish January and consequently unpublish all the nodes associated with it.

Does anyone have any ideas on how I might accomplish this?


texts: How to create a new field collection+fields in a programmatically added content type

texts:
I'm very new to creating modules and I'm creating a content type for the first time programmatically.

Creating the content type works fine, I've even added some fields. But now I'd like to create a new field in that content type which is a field collection.

I can't find a good spot on the internet that explains how I can add a new field collection to a new content type. All programmatically in one run.

Can anyone help me out how to achieve this?

It involves this contributed module.


texts: How to tell if you are on a view page in preprocess_page

texts:
I am trying to see if we are on a view page in the preprocess_page function in my MYTHEME.theme file.

views_get_page_view() gives me an undefined function error.

I want to get values from my view to display outside the view area in page.html.twig


texts: Filter a field based on the content type in a view(Drupal 7)

texts:
I need to remove a field for a view(Block) for a particular content type.

I have two different content types.One is Article and another is External News.

The following are the fields I added in the view.

Field:

      Content: Title
      Content: Post date
      Content: External URl
      Content: Last comment author
      Content: External URl

CONTEXTUAL FILTERS:
   Content: Has taxonomy term ID

FILTER CRITERIA
    Content: Published (Yes)  AND
    Content: Type (in Article, ...)
     AND
     Content: Has taxonomy terms (with depth) (= Technology)  AND | Settings
     Field: Tags

Here I need the field Last Comment author to display only when the content type is Article and not for External news.

Can Anyone help me how to filter the field based on the content type for a view block


texts:
I want to update a site from Drupal 8.9 to 9.0. After copying all files and trying to execute update.php, I get the following error:

  The website encountered an unexpected error. Please try again later.
  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "entity.manager". in Symfony\Component\DependencyInjection\ContainerBuilder->getDefinition() (line 1032 of vendor/symfony/dependency-injection/ContainerBuilder.php).

What can I do to update to Drupal 9.0?

My modules are up-to-date.

ctools
entity_reference_revisions
metatag
paragraphs
pathauto
redirect
svg_image
token
webform


texts: Drupal 7 Webforms 4, prevent submission if value of field is less than or equal to previous submission

texts:
I know that you can prevent submission if a specific value has previously submitted.

However can you prevent a submission if the submission is less than or equal to a previously submitted value.

example, you have a an existing value if 16.00 in the results. So you can not submit 0.00-16.00


texts: How do I hide an area in a template or layout if multiple regions have no content?

texts:
I am able to set this up using a single check for a content in a region, but what if say 3 regions must all have content before the area is displayed?

Here's what I use in my templates when checking for a single region:

<?php if ($content['region-1']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>

But for checking multiple regions, Something like this?

<?php if ($content['region-1']['region-2']['region-3']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>

Region 2 Content

  <?php print render($content['region-1']); ?>

Region 3 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>


texts:
How can i theming the comments like this in the node.tpl.php (with a new column after 3 comments)? I want to use this:

$cols = array();

$cols[] = '
' . t(`Kommentare`) . '
';

$comments = comment_render($node, $node->cid);
$comcolnum = 0;

foreach($node-cid as $comcol){
$comcolnum++;
$cols[] = '
' . $comcol['view'] . '
';
}

$cols[] = '
' . drupal_get_form('comment_form',array('nid' =>
$node->nid)) . '
';

print theme_table(array(), array($cols))

$node->comments, &comments or ... doesn`t work.
I think first i need to override the comment output in the template.php like this for Drupal 6:

function phptemplate_preprocess_node(&$vars) {
$vars['node']->comment = 0;
$vars['comments'] = $vars['comment_form'] = '';
if (module_exists('comment') && isset($vars['node'])) {
$vars['comments'] = comment_render($vars['node'], $vars['node']->cid);
$vars['comment_form'] = drupal_get_form('comment_form', array('nid' =>
$vars['node']->nid));
}
}

But! What i need to get every comment for the foreach function? I`m really new with PHP and Drupal API, but i want to learn it! Can someone show me the right way?

Greeting Bruno


texts: How to make a multi-site instance aware of shared module directory?

texts: My team inherited a Drupal 7 multi-site installation that was originally built with a custom installation profile and Drush make. I have all these sites running correctly in our environment now and want to bring an additional Drupal 7 standalone instance we support under this new multi-site configuration. I copied the database and created a corresponding subdirectory in the sites tree along with the proper edits to the sites.php file. The site does appear correctly when tested in a browser but the modules visible to the other instances are not seen by this site. Those modules are located under the profiles tree. I don't expect to need to use the install profile again and am inclined to copy the profiles/myprofile/modules directory contents to sites/all/modules to address this situation but am concerned about potential database dependencies. What is the best way to clean this up and have all multi-site instances aware of the same common modules?


texts: Assume that we have a list of titles on the left and a div on the right side of the page that displays posts. when I click one of the titles it first removes content of that div and then loads node content. how can I do this? is there any module or function to do that?


texts: Is it possible to make an exposed filter dependent from a contextual filter?

texts:
it seems like it is a trivial and common use case to me, but I have not found a solution so far: I have several vocabularies and I want to deliver a vocabulary via url into a contextual filter and dependent on the vocabulary I want to make the terms of this vocabulary presented as an exposed filter to the user.

As an example: There are vocabularies languages, IT and management, which should be delivered in url and go into a contextual filter. Lets say the delivered vocabulary is languages, then the user should see an exposed filter, where he can choose a language (the terms of the vocabulary) and sees all entities with the chosen terms.

I was looking really intense, but did not find a solution so far.

Thanks in advance


texts:
My question: Is it possible to make path to /% ?

I have path that goes categories/% and that works when I type categories/hats it returns me category hat with all product it's taged with.

I would like to be able to type url/hats and to have above explained functionality.

Is this possible and what do i change in view it is not possible to make path just /% ?


texts:
I am facing trouble while configuring a block. The block I configure is not showing up onmy website. I am using drupal 7 and the Touch theme. Here are the steps I do:
- in REGION SETTINGS i have selected "Highlighted"
- Visibility settings is:
 - pages (Only the listed pages) [http://example.com/news]
- Content types
 - Show block for specific content types> [Publish A News]
- Roles
 - I have made no changes here
- Users have not been set
Any ideas why the block is not showing up?


texts:
I am on a fresh Drupal 9.1.7 setup (tried PHP 7.4 and PHP 8.0).
When trying to install modules I get the following error:
Uncaught PHP Exception Drupal\Core\File\Exception\NotRegularDirectoryException: "temporary://update-extraction-03ad2725/$MODULENAME is not a directory." at /data/web/xxx/html/yyy/web/core/lib/Drupal/Core/File/FileSystem.php line 662

But when I check, the directory actually is in place:
drwxrwxrwx  2 xxx www-data 4.0K Apr 25 10:43 update-extraction-03ad2725

What do I need to do in order to be able to install modules via Web interface?
Installation via composer is working.


texts: Is it possible to include external libraries in a twig template?

texts:
I think I know the answer, because I tried to attach an external library like this:

{% set location = {'type': 'external'} %}
{{ attach_library('//example.com/example.js/v3/example.js', location) }}

This did not attach the desired library, am I missing something, or is this a non-starter?


texts:
I am trying to figure out the best way to manage some data. I don't want it to be accessible like nodes through any kind of URI. I know that, when entities are defined, I have to provide a URI callback. Is this callback necessary?

I mostly want to use entities because the API makes it easy (and standard) to work with data.


texts: How do I remove JOIN in hook_views_query_alter()?

texts:
I have a view with two filters (A + B). Filter B should only be included in the query, if a specific value in filter A is set (like a "conditional filter").

So I tried to remove the where condition of filter B in hook_views_query_alter by unsetting it:

if($remove_filter_B){
  foreach ($query->where as $condition_group_key => &$condition_group) {
    foreach ($condition_group['conditions'] as $condition_key => &$condition) {
      if($condition['field'] == 'field_B_to_remove'){
        unset($condition_group['conditions'][$condition_key]);
        break;
      }
    }
  }
}

I successfuly removed the where clause but the INNER JOIN on the table of filter B is still part of the query. How can I remove it? I've tried unset($query->tableQueue['node__field_B_to_remove']) but this doesn't work because tableQueue is protected.

Maybe I'm going the wrong way. Basicly I just want to have a "conditional filter".

Some aditional info: The view lists nodes of two different types. You can filter those node types with filter A. The field of filter B only exists in one of the node types. So if you choose filter B you only get nodes of one type. And when you select the other one in filter A you get no result. And that's the issue.


texts:
I can log in, perfectly fine, but can't get logout to give me a JSON response. Currently, I can only do POST to

d8.com/user/logout?csrf_token=123&?_format=json

and that would log out, even though the token 123 is not the same as the given csrf-token at login or the logout token. This doesn't work without the token query, even though cookie/session isn't enabled anywhere

  ("message": "'csrf_token' URL query argument is missing.").

The logout happens when hitting a 403 forbidden on that URL.

Other info:
csrf_token=123 is the actual query, doesn't need to be csrf-token or the log out token is given at login
Version: 8.5.3
The only basic_auth turned ON, at all endpoints.


texts: When is node_search() in the node module called?

texts:
Someone has made changes to core, and specifically the node_search() function in the node module.

I'm not familiar with this function. What does it do, and under what circumstances is it being called?


texts: Only one module implements hook_tokens()?

texts:
I've declared a [module-name]_tokens() hook but when I output the contents of module_implements('tokens'), only my module appears in the list.
I know that there are many more modules that implement hook_menu(); why do I get only my module listed? Where shall I look for possible errors?


texts: Why Conditional Fields Validating the Hidden Fields?

texts:
I have preset sizes like small, medium and large and an option to provide custom size. If some one selects custom option from a select list the measurements fields appears through conditional fields and if some one select small medium or large the measurements fields hides.

The problem is when I am submitting a form by selecting Small, Medium or Large option from select list it gives error that measurements fields are required.

I have tried to add additional condition to make the fields optional if the select list has the values small, medium or large but still getting the same error.


texts:
I have Drupal 7 with CKEditor 3.6.2.7275 under Wysiwyg module. In configs of Wysiwyg I unchecked all the checkboxes for "Cleanup and output" category. Plus unchecked "Limit allowed HTML tags" for Full HTML text format.

When I try to edit the page, containing javascript inside, the <script type="text/javascript"> is inside the <textarea> for content editing. But it's not shown by CKEditor when I click source button. So it's undoubtedly CKEditor filtering.

What should I do to make CKEditor show javascript?


texts: What is the relationship between field_data_field_ and field_revision_ tables?

texts:
It seems that the field_data_field_ and field_revision_field_ tables contain exactly the same columns and data, except the revision table contains a row for every revision whilst the data table only contains a copy of the latest revision.

What is the point of having the 2 tables ?  Which table is accessed when a node is loaded ?


texts: How to render a view as a entity field on form edit?

texts:
I'm looking for a module (or alternative solution) to render view in the field.

Similar to Viewfield, but it should be rendered when filling the form (Entityform or node edit).

The purpose for that is to include Commerce views in the entity form (such as commerce_cart_form, commerce_cart_summary, commerce_payment_order) which are actually views.


texts: With managed file, dynamically set fileName and #upload_location

texts:
In a form I want to bulk upload jpgs renaming them using exif date information and dynamically setting the #upload_location according to the value of a textfield in the same form.
I have no problem with accessing the exif date information. What I don't know how to do, is dynamically set the file name and file path (actual location on the server) programmatically.
This is my form upload element:
$form['images'] = array(
  '#type' => 'managed_file',
  '#multiple' => TRUE,
  '#upload_validators' => array(
    'file_validate_extensions' => array('jpg'),
  ),
  '#upload_location' => 'public://photos',
  '#required' => TRUE,
);

$form['file'] = [
  '#type' => 'fieldset',
  '#title' => $this->t('File'),
];

$form['file']['name'] = [
  '#type' => 'textfield',
  '#title' => $this->t('File name'),
  '#description' => $this->t(
    'Is suffixed by the exif creation date-time plus fid cleaned for urls. If not set the original file name will be used.'
  ),
];

$form['file']['path'] = [
  '#type' => 'textfield',
  '#title' => $this->t('File path'),
  '#placeholder' => 'path/to/directory',
  '#description' => $this->t(
    'Path to the files sub-directory, default is "photos". Sub-dirs will be create if necessary.'
  ),
];

I've tried using something like this in both validateForm() and submitForm().
$images = $form_state->getValue('images');
$file = File::load( $images[0] );
$file->setFileName("xxx2");
$file->setFileUri("public://photos/test/xxx2.jpg");

Although this changes the values of the $file object, it doesn't change the real path. The jpg files are also still in /sites/default/files/photos/ with their original name plus a unique counter.
So to repeat my question:
How can I set the upload_location and the fileName of a managedFile dynamically and programmatically in a submitForm() or validateForm() function using methods that are not marked deprecated in drupal 8.


texts: New content type not listed in content types

texts:
First time I created the content type 'address', I simply clicked save, not 'save & edit fields'. As a result, my new content failed to be listed under admin/structure/types. Then I simply tried the same thing again, with the same result of nothing being listed. When I did this though, A Drupal message said that the content type 'address' had been updated.

3rd time I clicked 'Save & edit', I wanted to manage fields, but that generated a URL that said www.domainname.com//fields instead of www.domainname.com/address/fields. Also a notice came : Notice: Undefined index: address in _field_ui_bundle_admin_path() (line 325 of C:\xampp\htdocs\hosting\sites\drupal7\modules\field_ui\field_ui.module).

Note that I'm using the module Automatic nodetitles


texts: Is there any way to number Paragraphs rendered so as to have a numbered list rendered?

texts:
I’m putting together a project that requires a content type that has a numbered “How To” list in Drupal 7.5.x.

I am using the Paragraphs module and so far the basic concept of having paragraph blocks of how to “steps” is working as expected. Users are able to “Add another Paragraph” to add each additional step and the steps render correctly on the front-end display as expected.

But while that’s all fine, I’m having a heck of a time understanding how I can have Drupal/Paragraphs automatically number each paragraph so it would look like—for all intents and purposes—something like this; literally I just need that number to the left of each Step …: item and that’s it:

Step One: Do this.
Step Two: Do that.
Step Three: Do something else.

I have been playing around with the Custom Formatters module and it almost seems like that might be my solution: I could use a custom formatter that uses PHP to do something like this. Let’s assume this is what outputs the title for each paragraph field_title value with a PHP custom formatter:

return $variables['#object']->field_title['und']['0']['value'];

So I should be able to do something like this to get a number/order prepended:

return $count . ': ' . $variables['#object']->field_title['und']['0']['value'];

Of course $count is just some arbitrary pseudo-code I am placing for example’s sake, but is this the right approach? Or am I barking up the wrong tree. FWIW, I am poking around the values of the output via the Devel module and don’t see anything useful that would related to count/order.


texts:
I use the default taxonomy view (with default path: /taxonomy/term/%) to display videos that have been categorized at the time of their upload. The viewer has access to an exposed filter that allows him to select like 10, 30 or 40 video thumbnails per page (default is 10.)

The Pathauto taxonomy pattern for all video paths is:
[term:vocabulary]/[term:name]
Token is enabled.

The url of the landing page is correctly displayed www.example.com/videos/sports when the vocabulary "videos" and the term "sports" are selected through a menu.

But if, on that same page, I select to view 30 video thumbnails per page instead of 10, the url changes to:

www.example.com/taxonomy/term/1989/0?items_per_page=30

This appears normal since the the view path is /taxonomy/term. The content displayed is correct, but the page theming is totally out of wack.

How do I keep the url at www.example.com/videos/sports/0?items_per_page=30 ?

Shouldn't Pathauto handle this?


texts: Adding custom html and css to views header and footer

texts:
Is it possible to add custom HTML and CSS in views header and footer using the administrative UI? I am trying to add a header to my view but that is not giving me any option through which I can add HTML and CSS like the options which are given to us when we add fields in views.
I have tried adding a header using Global Textarea but in this, we can only write HTML not CSS. Kindly tell how can we add HTML and CSS both to the header.


texts: Unable to run database updates via Drush - Call to undefined function batch_get()

texts:
Having some difficulty running database updates via drush after updating modules in the codebase.  This is the error that is being reported:

Error: Call to undefined function batch_get() in /root/.config/composer/vendor/drush/drush/commands/core/drupal/batch.inc on line 92 #0 /root/.config/composer/vendor/drush/drush/includes/batch.inc(98): _drush_batch_command('11459')

This is only happening on our production environment, our staging environment is identical and works without issue.

We are able to run the updates via update.php; but we are planning to migrate to the new core media module in the coming days, and those updates bring the site down until database updates are run so update.php will not be an option.

The database is located on another server, but we have no problem connecting to that server via tools such as drush sql-cli.

We have also tracked down the 'undefined' method in question and verified it to be in existence.

Many thanks in advance for any help.


texts: Using taxonomy hierarchy in Views arguments

texts:
I'm building a store with products organized with a hierarchal taxonomy. I'd like the paths for Views showing products to reflect the taxonomy hierarchy. For example, products/category-a/subcategory-a, products/category-b, etc. (In this case, products will only be a member of one category/term at a time, and terms will either have child terms or products associated with them, but not both - with the example paths above, products/category-a would list the child terms of the Category A term, but no products.)

I can build a view with a path like products/%, and that works just fine with products/category-b, but I can't figure out how to get that working with products/category-a/subcategory-a - it throws a 404. I've thought of implementing a Views alter hook to alter $args to only use the last argument, but the 404 is happening from a failure in menu_get_item() - before any Views code has a chance to run (and call alter hooks).

I can't think of any other pleasant ways to work around this, but surely I'm not the first one to want to try to implement a catalog like this… What's the most correct way to do it? (Ugh, I feel like such a site-builder n00b.)


texts: Javascript related problems when using old versions of IE and a proxy server

texts:
I have a site that is fairly javascript heavy.

It uses the edit module with some custom javascript overrides, some other plugins like fancy scrollbars, flexslider, image cropping, etc. as well as a bunch of custom js that does alot of ajax loading of content.

The homepage is basically a solr+facetapi search page that returns a huge grid of images, which are effectively cropped & positioned with js after they load (using imagesLoaded to wait before processing).

In all modern browsers everything works fine.
In IE when not using a proxy, everything works fine.
In IE <= 10 strange things happen.

Normally what happens is the page starts loading and the images start appearing individually as they have loaded.

With IE + proxy the page starts loading and then seems to stop, while all the js & images are loading in the background, then after about 30 seconds (much, much longer than the page would take to fully load normally) all of the images appear at once.

Also, normally as images load in the are visibility: hidden, cropped & positioned and then are visibility: visible, but in this case not all of the images end up with visibility: visible, but the images have loaded in, you can see them with developer tools tweaking of css.

Enabling or disabling of js/css aggregation doesn't make a difference, nor does cache clearing.
After a little debugging I noticed that the imagesLoaded plugin was not firing at all until the end and then was firing for all images at once, instead of normally it firing as each image loads, but there didn't seem to be any reason for this.

Setting the proxy server to "cache deny all" seemed to help the problem but it wasn't as good as it is normally in non-IE browsers (IE11 seems fine too).

Has anyone seen behaviour like this before or does anyone have any ideas of things to investigate?

TL;DR:
I have a site where everything loads normally except for users running IE <= 10 and a proxy, in which case the page loads extremely slowly and javascript doesn't run as expected.

Has anyone seen anything similar or have any ideas on what it might be.


texts:
I have an array that I stock in the browser's storage. I retrieve it in Javascript.

I'd like to use those values to display a view. They IDs represent a nid.

I already created a view, took a wildguess and decided to use the contextual filters, allowing me to pass parameters in the URL.

But now, I'm stuck.

Any hints/tips ?

Thank you


texts:
I've created a module called hotel_reviews.

I've created the route node/{node}/reviews using hotel_reviews.routing.yml.

hotel_reviews.content:
  path: '/node/{node}/reviews'
  defaults:
    _controller: '\Drupal\hotel_reviews\Controller\ReviewsController::content'
    _title: 'Reviews'
  requirements:
    _permission: 'access content'

I then tried to add a local task using hotel_reviews.links.task.yml.

hotel_reviews.content:
  route_name: hotel_reviews.content
  title: 'Reviews'
  base_route: node.view
  weight: 100

I can now access the content defined by my controller at node/1/reviews, however when I go to node/1 I don't see a reviews tab.

What am I doing wrong?

I've been using the following documentation so far:

D7 to D8 upgrade tutorial: Convert hook_menu() and hook_menu_alter() to Drupal 8 APIs
Providing module-defined local tasks
Structure of routes


texts:
I'm trying to create a rule that will unpublish a product display only if it's a certain type of product once stock reaches zero.
I can't seem to find any good recipes to do that. I don't know anything about the inner workings of the Rules module and everything I've blindly tried doesn't work.


texts: How to get the source url for RSS feeds by the Feeds module?

texts: When using Feeds for displaying external RSS content on my site, it doesn't work because Feeds turns links like http://externalsite.com/abc into mysite.com/abc. Aggregator gives the desired result, i.e. the complete source url http://externalsite.com/abc. Can I get the same automatic result using Feeds? If yes, how?


texts:
Is it possible to show node edit form on preview page without need to click on "back to content editing"? If yes, how?

Why?

I'm migrating a website from older Drupal version and "my" users are used to original behaviour. The target audience is not very experienced with computers, so any changes to them are scary and unwelcomed.
It's extra click-and-wait and even I found it bit annoying during development; I couldn't get used to it during 3/4 of year I'm working on the migration.

Note:  I found that NodePreviewController class is responsible for the preview page and that NodeForm class is responsible for the edit form, but I'm missing knowledge of whole picture, i.e. how to connect these two together in Drupal-way without breaking anything and how to connect the form to previously submitted data.


texts: Define custom view page template with theme_hook_suggestions

texts:
I would like to define 'theme_hook_suggestions' for a custom views-view.tpl.php file.

To achieve this, I wrote the following code into my template.php file:

/**
 * Implements hook_preprocess_views_view().
 */
function MYTHEME_preprocess_views_view(&$variables) {
  // Some logic to decide if the hook_suggestions should set or not
  // ...
  $variables['theme_hook_suggestions'][] = 'foo';
}

After that, I created a copy of views-view.tpl.php in the templates folder named foo.tpl.php.

Sadly, my template file is ignored by Drupal and the default views-view.tpl.php file is rendered on the page.

What's the matter? I debugged the theme_registry and the template path should be correct (points to my theme).

Update
The target is that I can switch between two template files which are defined in my preprocess function (see above). Because in some cases, my layout markup is significant different as in other cases.

I don't want to use the same template file for both cases; when I do this, the file is full of tousands of if() just for adjusting the markup for some cases.


texts: Drupal calling "is_dir" over 4000 times?

texts:
After having troubles on loading time of a very important Site I installed XHPROF and looked over the statistics to see where I can improve my code.

I found something interesting that i don´t understand. Drupal calls "is_dir" over 4000 time on nearly every request and this takes about 800ms to execute. Why is that and is there a way to speed that up?

By a loading time of two to four seconds is 800ms take a big part.


texts: Calling another function using drupal_get_form

texts: How can I call a function using drupal_get_form when a submit button is clicked. My situation is that i have a custom module where there is only a submit button. So when that submit button is clicked I want to call a particular function. How can I achieve it through drupal_get_form.


texts: How to set limit for excel parser Drupal 7

texts:
I am importing users from Excel sheet with Feed importers. In my local WAMP server I can import more than 170 users. But when I am trying on my server, it is not working. It's showing:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging
  information follows. Path: /batch?id=2906&op=do StatusText: Internal
  Server Error ResponseText:

So I thought of limit by code. So I am using HOOK_feeds_after_parse where I will get all $results. I am counting the results with count($results), if it is less than 150 then show a message(drupal_set_message()).

It is stopping if it is more than 150 but giving more errors like username and email is missing. Can you please help me with this? Alternatively, is there anyway to limit number rows to the parser?


texts: Drupal 7 update field programatically and generate field names

texts:
I'm here still learning with drupal 7 but now I have a new question about a node create programmatically,I hope you can help me.

I want to generate all node fields names programmatically and then set a lavue on each one.

To store each field from node I generate the names of the field witn an array with each name, this is because I want to make  function to indicate the names of the fields of the node that I want to fill.

The problem is that my code is not working to fill the nodes, maybe because my fields names are bad generated. I generate and fill them this way:

    $nodefields = array('areaid', 'areaname');

    foreach ($nodefields as $fieldname) {
            $node->$fieldname['und'][0]['value'] = $row->$fieldname;
            }
    node_save($node);

The rows are obtained by a query to a external db (column has the same name as the field), that's fine, the records are ok, if I fill them manually like:

$node->areaname['und'][0]['value'] = $row->$areaname;

Works ok, but I can't make it work with a loop to generalize that part.


texts: Treating string field as numeric to use as an exposed filter

texts:
I have a field in my users' profiles that has been defined as varchar initially even though it holds numeric values. I'm trying to use that field as an exposed filter and perform "greater than or equal" operation on it; however, since it's a varchar field, View doesn't give me that option.

In my module, I have come up with these two hooks to do a workaround:

function MY_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'manage_users' ) {
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_count.field_count_value' ) {
                $query->where[1]['conditions'][$key]['value'] = (int)$query->where[1]['conditions'][$key]['value'];
                $query->where[1]['conditions'][$key]['operator'] = '>=';
                break;
            }
        }
    }
}

function MY_MODULE_views_data_alter(&$data) {
    $data['field_data_field_count']['field_count_value']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['filter']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_value']['argument']['handler'] = 'views_handler_filter_numeric';
    $data['field_data_field_count']['field_count_format']['argument']['handler'] = 'views_handler_filter_numeric';
}

The first hook seems to be working fine and successfully changing the operator from LIKE to >=; however, that's not enough for me because it still thinks 2 is greater than 15. So I added the second hook to make sure the field is actually treated as numeric, but that doesn't seem to have any effect on how the results are returned and it still thinks 2 is greater than 15.


texts: I have WYSIWYG and CKEditor 3.6.6.1 and want to install the latest CKEditor 4.6.1

texts:
My goal is to paste images (best if copied from word together with text) directly without uploading them first.

I got a D7 site with WYSIWYG installed. The module tells me it uses the CKEditor 3.6.6.1 library. In fact, there is no CKEditor module installed, but in the libraries path I see a ckeditor folder.

I tried to install the module pasteFromWord, and I found it didn't work with my a local copy of my site. So I looked around, and I found there is a newer version of CKeditor (4.6.1) rewritten with lots of features like embedding pictures, and it is open source too. There is only an older version of CKEditor as a Drupal 7 module, and it is driving me nuts to install anything that works.

I read about problems with WYSIWYG and I disabled it, but I cannot uninstall it, so I cancelled the whole directory under modules. I installed the latest Drupal CKEDitor (Dev) but all I see in my text field is htmlcode in full html mode. There are no editor icons. I put higher values for the memory settings in settings.php, restarted the server, cleared the cache, tried all sorts of thing suggested in Why does the Wysiwyg module and Ckeditor library not show the CKEditor when editing a node?

All tests are done as user1. By now, I get a simple text field in plain and filtered HTML mode; in full HTML, the text box body simply vanishes.

In Mozilla the Console gives:
TypeError: a(...).on is not a function
 js_8iXNyfjLJ1tJPju6nAtk8ETos8oLn9Arp0f2Z5uBPaQ.js:850:1412
TypeError: CKEDITOR.dialogCommand is not a constructor
 plugin.js:4:43
in http://localhost:8080/drupal7bis/sites/all/modules/ckeditor/ckeditor/plugins/SimpleImage/plugin.js which is one of the few plugins I enabled so far (nearly all are installed though because indeed I took the full package) and it reads:
CKEDITOR.plugins.add( 'SimpleImage', {
    icons: 'simpleimage',
    init: function( editor ) {
        editor.addCommand( 'simpleimage', new CKEDITOR.dialogCommand( 'simpleimageDialog' ) );
        editor.ui.addButton( 'SimpleImage', {
            label: 'Add a image',
            icons: 'simpleimage',
            command: 'simpleimage'
        });

    CKEDITOR.dialog.add( 'simpleimageDialog', this.path + 'dialogs/simpleimage.js' );
}

});

When I disable this plugin, only the first error remains. The body does not vanish any more in full mode, but still no editor appears.
There are no recent records in watchdog...


texts: Googlebot and AmazonBot trying to access every Drupal page I edit

texts:
Ok, this is extremely weird.

The point is, everytime I edit a node on my website, and then go to the "recent logs" page, I always see a request (with "access denied") from an IP owned by Google or Amazon for the same node/edit page I had just visited, right before (or after) the line saying that i had modified that node.

I've tried from 2 different PCs, using different browsers... same behaviour.
Another drupal site on the same server doesn't have this "issue".

What is happening? Why is GoogleBot stalking me?

I've tried copying the entire site to another domain and the result is absolutely the same.

@beebee: they are completely different sites... it would be like looking for a needle in a haystack and I have no idea of where to start from.

@Alfred Armstrong: no google toolbars or other weird extensions... plus, I was wondering: how can they be so fast? I mean, I see the request immediately... I'm thinking more of a logging error from Drupal for obscure reasons.


texts: Do I have to validate() user entity saved programmatically?

texts:
I have a custom module saving user accounts from a customer API.

For this I use the \Drupal\user\Entity\User::create method, and I initialise the user account with the code above:

  /**
   * Save a Drupal user using `mail`.
   *
   * @param array $data
   *   The User data to save.
   *
   * @return bool|int
   *   Result: SAVED_NEW or FALSE.
   */
  public static function saveUser(array $data) {
    // Only if user exists on API
    if (empty($data['mail'])) {
      return FALSE;
    }
    // Create the user
    $email = $data['mail'];
    $user = \Drupal\user\Entity\User::create();
    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

    // The Basics
    $user->setEmail($email);
    $user->setUsername($email);
    $user->set("init", $email);
    $user->set("langcode", $lang);
    $user->set("preferred_langcode", $lang);
    $user->set("preferred_admin_langcode", $lang);
    $user->enforceIsNew();
    $user->setPassword(user_password());
    $user->activate();

    // Save user.
    return $user->save();
  }

I like to look for a good way of doing things and to read about getting D9 ready for my modules. When it is necessary, I also inspect the core code to see the available methods and how core modules are made to inspire me.

I found this interesting topic about Entity Validation API, where it speaks about using validation on entities. I also found that user object has methods to know if a validation is necessary and to validate, and the preSave method will throw an exception if the validation is necessary and not done.

All the examples and code snippet I found on internet about creating a user programmatically never use any kind of validation, and I wonder if this is something new or if it is just not really necessary for my case.

As I said, I save data from a remote API, and I do not manage the quality of the email address I use as email and username. I also do not verify if those values already exist.

Should I add something like this ?

// Entity validation
if ($user->isValidationRequired()) {
  $violations = $user->validate();
  if (count($violations)) {
    \Drupal::messenger()->addError($violations[0]->getMessage());
    return FALSE;
  }
}