texts: Disable the toolbar module in install profile

texts: How do I disable the toolbar module in my make file / profile info / install file?


texts:
Is there a way to get Drupal internal path from the external URL? I need to get node id (or any other internal path) from the URL that user specifies in the textfield. External URL in this case is not the URL of current page, it is arbitrary URL that is entered by user.

For example:

Base URL: http://www.example.com/drupal

Alias of node/101: foo/bar

User input: http://www.example.com/drupal/foo/bar or http://www.example.com/drupal/?q=foo/bar

Expected result: node/101 or foo/bar

The problem explained:

drupal_get_normal_path() only returns normal path if internal alias is given. In this case internal alias from external URL needs to be extracted but there are no internal Drupal function that would do that directly.
If site has Clean URLs enabled, request path in external URL can either be in "q" argument (?q=foo/bar) or in URL itself (/drupal/foo/bar).


texts: How to get product image URL from product page?

texts:
I'm developing a module for Drupal Commerce - Drupal 7 and I need to get the product image URL from product page but I couldn't find a solution for this.

I'm successfully fetching the product name, title, url but not the its image URL which really bothers me as I am used to WooCommerce where there is a very simple way of getting the image URL.


texts: How do I enable a custom JS file in my Drupal site?

texts:
In my Drupal themes' folder I've created a file named "custom-js.js".

I created this file to use 2 jQuery manipulations on a small text block that appears in all pages of the site.

My question is, how do I enable this JS file? How do I "link it" with Drupal, so that it's actually being used in my site?


texts: Views Output field as a link - Two tokens, use only one of them

texts:
I have content type which has field_pdf.
I have made view to show content and there is a field which has set: Output field as a link.
In link path settings I have two tokens: [field_pdf][path]. Idea is to link field either straight to PDF (if there is PDF file in node) or to content node.

How to get view to use only [field_pdf] when this field_pdf has content and not use [path] at all?

Now I'm getting double url for example: http://url.com/pdf-file.pdfhttp://url.com/pdf


texts:
I added the following code in my .htaccess file :

<IfModule mod_headers.c>
  Header set Set-Cookie HttpOnly;Secure
  Header always set X-XSS-Protection "1; mode=block"
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-Frame-Options "DENY"
  Header set Content-Security-Policy "script-src 'self' https://apis.google.com"
  Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
</IfModule>

and the Administrator menu drupal no longer appear on my site. When I delete this line, the menu reappears. How to solve this problem ?

Header set Content-Security-Policy "script-src 'self' https://apis.google.com"


texts: How to creat a page display comments list of users

texts:
I try to make every users of my site can view their own and others' posted comments (like "profile:user comments history").

Although the Tracker module can do it, it is not the way I want: It doesn't display the comment but the title of the article to which the comment belongs to.

I am trying with the Views module 7.x-3. I created a comment type view to display comments and add a relationship "Comment: Author". I am stuck here: user1 can view user2's, user3's "profile:user comments history" so the value of "Comment: Author uid" (Filter criteria) should change with the profile pages.

The path of user profile page is /user/% and the arg(1) is the id of users. So I want to make "Filter critera" -> "Comment: Author uid (= < ?  php echo arg(1) ; ?>)", but it does not work.

If the Views module can't do this, please tell me some other modules (small and simple is best) that could make it.


texts: Is there a way show user that the content has been automatically translated?

texts:
I am using the Translation Management Tool module to translate my nodes automatically. What I want is for users to see whether the node they are seeing (in their language) is the translated, or the original one. I managed to make the translation (when node is saved, it is translated) and with rules I can change value of e.g. some integer field, but it changes on both nodes: original and the translated one.

How can I change it only in translated one?


texts: form ajax forget's changes made in previous ajax callback calls

texts:
Why do changes don't get saved in $form, or what is it that's overriding it?

I would like to set custom class to multiple fieldsets in an ajax callback function:

if (something) {
  $form['fieldset_01']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_02']['#attributes'] = array('class' => array('custom_class'));
}
elseif (somethingelse) {
  $form['fieldset_11']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_12']['#attributes'] = array('class' => array('custom_class'));
}

return $form;

When $form is returned, the element that I have set in this call is rendered fine, with a new CSS class but the elements I have rendered in previous calls have lost this new class, as if they were rendered with default values.

EDIT: my form creation function

function mynode_form($form, &$form_state) {

$nid = $form_state['values']['nid'];

$ajax = array(
'callback' => 'mynode_ajax',
'wrapper' => 'mynode_form',
'event' => 'change',
'method' => 'replace',
);

$node = node_load($nid);
$title = $node->field_title['und'][0]['value'];

$form = array();
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['nid'] = array(
  '#value' => $nid,
  '#type' => 'hidden',
);

$form['fieldset_0'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 0',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_0']['textfield_0'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 0?'),
  '#ajax' => $ajax,
);

$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 1',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_1']['textfield_1'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 1?'),
  '#ajax' => $ajax,
);

if (isset($form_state['triggering_element']['#name'])){
  $key = $form_state['triggering_element']['#name'];
  switch($key){
    case 'textfield_0':
      $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b',   'c'));
      $form['fieldset_1']['#attributes'] = array('class' => array('a',   'b'));
    break;
  }
}
else{
  //only the first time
  $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b'));
  $form['fieldset_1']['#attributes'] = array('class' => array('a', 'b'));
}
return $form;
}


texts:
I am trying to create a custom field module for views, but I keep getting this error when I add the field to the view.

  SQLSTATE[42S22]: Column not found: 1054
  Unknown column 'views_report_state_field' in 'field list'

This is the code I am using.

views_report_state.info

name = Views Report State
description = Turns short abbreviated states (ex: TX) into fully readable names (ex: Tx = Texas)
package = Views
core = 7.x

files[] = views/views_report_state_field.inc

views_report_state.module

function views_report_state_views_api($module = NULL, $api = NULL) {
  return array("api" => 3);
}

views_report_state.views.inc

function views_report_state_views_handlers() {
  $handlers = array(
    'info' => array(
      'path' => drupal_get_path('module', 'views_report_state'),
    ),
    'handlers' => array(
      'views_report_state_field' => array(
        'parent' => 'views_handler_field',
      ),
    ),
  );
  return $handlers;

function views_report_state_views_data() {
  $data = array();
  $data['views']['views_report_state_field'] = array(
    'title' => t('CRF: Convert US-State Abbreviations'),
    'help' => t('Converts State Abbreviations to their full name'),
    'field' => array(
      'handler' => 'views_report_state_field',
    ),
  );
  return $data;
}

views_report_state_field.inc

class views_report_state_field extends views_handler_field {

  function render() {
    return "working!";
  }

}


texts: Node theme template override isn't working

texts:
I'm using the paid theme md-alpine and I added a content type called webinars, and a node template for webinars node--webinars.tpl.php

The only thing I put in the page is  and I only get an HTML page with no CSS.  Am I supposed to add a call to the node--webinars.tpl.php page somewhere?

EDIT: I changed dpm to print_r and the rest of the theme printed.  Put it back to dpm and it doesn't load.

This is the raw output of the page:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>

Home

About

Gallery

Staff

Testimonials

Donations

Blog

Contact

Members

                Posted by admin

Test

                21 June 2014

Primary tabs

View(active tab)

Edit


texts: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?

texts:
I have seen many times people saying not to use custom PHP/PHP filter (from the Drupal UI) in blocks, nodes, views-args, rules, etc. I have searched around a bit and haven't found much, it seems like this is a Drupal best practice that all "just know".

I understand it poses a potential security risk especially in the hands of end users or people new to Drupal or PHP, but as a developer/site builder what are the real reasons to not use custom PHP from the Drupal UI?


texts:
I am trying to style a page I made, the url to the page is:

http://127.0.0.1:13080/nieuws

I copied page.tlp.php to my template folder and renamed it page--nieuws.tlp.php and adapted the file but the changes don't come through. I also flush all cache every time.

I tried to add this to my template.php (found it on this website) but it still doesn't work, could anyone help me out?

function asap_preprocess_page(&$variables) {
  if (arg(0) == 'nieuws') {
    // This will look for template named page--nieuws.tpl.php in your theme.
    $variables['theme_hook_suggestions'][] = 'page__nieuws';
  }
}


texts:
As twig does render templates in the UI language instead of the content language, all the t() functions deliver the default language. In my case this is wrong as the ui language is german but the content language can vary.

Can I tell the t() function to deliver the translation for Spanish for example?


texts: What is the best way to hide drupal block which we have created in module

texts:
I am using GeoMap module to show maps of organizations. I am setting the data for it in the block i have defined in the custom module. I don't want to display that block (but the code in that block should be present in that page code so that GeoMap could find it and render a corresponding map.
OR is there any other better way to accomplish same


texts: How to add a subtitle field to a block view?

texts:
I want to add an additional subtitle to a block view in Drupal 8. For example my View would be showing News on the site. So I want the title to be 'News' and then a subtitle underneath 'My Subtitle'. Then the list of news would follow. How would I do this? Can i add additional fields just like with custom blocks?

In the end it should look something like that:

 Subheadline

 Headline

      Block Content


texts: Is it possible to have a specific page.tpl.php for mobile devices?

texts: Background is, that the "desktop-version" of the website will have some external advertisements added via javascript-tags. Due to the nature of these adverts, they don't scale down with the rest of the responsive elements. I could just hide them via CSS and Media Queries, but then they would load anyway and slow down loading times.


texts: I cannot find any good examples on how to make a module configuration translatable. Could someone give me a starter example to build off with?


texts: How to disable radio button when Commerce Stock = 0?

texts:
I'm using Commerce Kickstart and I have a term reference for Size, and I'm using the Check boxes/radio buttons widget with Commerce Stock and Commerce fancy attributes.

Currently, when the stock of number of a product is 0, the "Add to cart" button is disabled. I would like to take this further by disabling the radio button so that the user can see that a product is out of stock before clicking "Add to cart".

I've tried disabling the product when its stock reaches 0 here: Disable product when out of stock but then the radio button just doesn't get printed when the product is disabled (ie. only printing S,L and XL when M is out of stock) I would still like to print the radio button option for "M" but as a disabled button.

How may I achieve this? Thanks!


texts: Change Entity Value In hook_feeds_presave()

texts:
I am trying to modify data coming from a feed before it saved to a node by using hook_feeds_presave().

I have code that looks like this:

my_module_feeds_presave(FeedsSource $source, $entity, $item) {
     $email =  $item['email address'];
    //Remove "NOT GIVEN" from the email column to stop errors
    if($email == "NOT GIVEN"){
        $entity->field_email['und'][0]['value'] = '';
    }
}

I would think that when the node is saved that value in the email filed would be blank. However, it is still saving the value of NOT GIVEN.

If anyone can please point me in the right direction with this I would appreciate it.

Thanks,

Josh


texts: How to display inbox messages and sent messages order by date - private message module

texts:
In private message module inbox and sent messages should be display by time wise.

Right now,

It is displaying where the unread messages list first and then the read messages list second.

But based on my requirement

All the messages should be displayed in date order weather it is read or unread

How can I do this?


texts: Drupal 7 Module to Set image src to a URL

texts:
I am trying to do something pretty basic but I just cannot find the right module.

All I want to do is have a field type or widget that I can use in a content type that will set the image tag's src property to a URL without actually adding the file to Drupal.  The images for our site are located in a database and are accessible via a URL.

I tried the Media module but that adds the file to the Drupal images folder.

There's got to be a module for this.  Anyone know the right one?

Thanks.


texts: Sorting result of views using data from another table

texts:
Sorry, pretty new to Drupal and Views so hope you guys can give me a few pointers.

I am trying to display a list of popular users on the front of my website. Noticed that pagewatchers has a table with the user id to visited urls like so (sid=>"9900",url=> "user/1234").
I have the basic idea of a query that would sort users against the count of urls matching 'user/$user->uid%'
though unsure how i would do this in views? Do i use the sort criteria and Global:PHP? Any help is much appreciated.


texts: Access Denied when visiting my custom route

texts:
I have a custom module with machine name "mymodule". The mymodule.info.yml file looks like this:
name: My module
type: module
description: 'My first drupal module'
core: 8.x

Then I have a src/Controller/FirstController.php which looks like:
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Defines FirstController class.
 */
class FirstController extends ControllerBase {

/**
 * Display the markup.
 *
 * @return array
 *   Return markup array.
 */
    public function content() {
        return [
            '#type' => 'markup',
            '#markup' => $this->t('Hello, World!'),
        ];
    }

}

Finally, I have mymodule.routing.yml that looks like:
mymodule.content:
  path: '/mymodule'
  defaults:
    _controller: '\Drupal\mymodule\Controller\FirstController::content'
    _title: 'My first route'
  requirements:
    _permission: 'access content'

When I go to the url /mymodule, I get Access Denied.
How can I fix the permission denied?
I saw a similar issue here but the answer does not seem to work for me.


texts: Unsure how to define an entity type using Entity API

texts:
I'm here because of this:

  EntityMalformedException: Missing bundle property on entity of type contacts. in entity_extract_ids()

I'm trying to create my own entity. Can you identify what is incorrect or missing about my entity configuration?

I am using the Creating your own entities with Entity API guide for setting up a new module using entities.

For my needs, I only need one entity type. The example creates two entity types, one called "task", and another called "task_type".  So I did my best to eliminate the "task_type" sections, but I'm getting the above error and am not understanding what to do about the bundle type.

This is my hook_entity_info().

/**
 * Implements hook_entity_info().
 */
function contacts_entity_info() {
  $return = array(
    'contacts' => array(
      'label' => t('Contact'),
      'entity class' => 'Contacts',
      'controller class' => 'ContactsController',
      'base table' => 'contacts',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'ckid',
      ),
      'bundle keys' => array(),
      'bundles' => array(),
      'load hook' => 'contacts_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'contacts',
      'access callback' => 'contacts_access',
    ),
  );

  return $return;
}

This is my custom controller. (Do I even need this?)

class ContactsController extends EntityAPIController {
  public function create(array $values = array()) {
    global $user;
    $values += array(
      'mail' => '',
      'notes' => '',
      'created' => REQUEST_TIME,
      'changed' => REQUEST_TIME,
      'uid' => $user->uid,
    );
    return parent::create($values);
  }

  public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
    $wrapper = entity_metadata_wrapper('contacts', $entity);
    $content['author'] = array('#markup' => t('Created by: !author', array('!author' => $wrapper->uid->name->value(array('sanitize' => TRUE)))));

    // Make Description and Status themed like default fields.
    $content['notes'] = array(
      '#theme' => 'field',
      '#weight' => 0,
      '#title' =>t('Notes'),
      '#access' => TRUE,
      '#label_display' => 'above',
      '#view_mode' => 'full',
      '#language' => LANGUAGE_NONE,
      '#field_name' => 'field_contact_notes',
      '#field_type' => 'text',
      '#entity_type' => 'contacts',
      '#items' => array(array('value' => $entity->notes)),
      '#formatter' => 'text_default',
      0 => array('#markup' => check_plain($entity->notes))
    );

    return parent::buildContent($entity, $view_mode, $langcode, $content);
  }
}


texts: Giving a default value to a password element in D7 form API?

texts:
I wrote a custom feeds fetcher class that does an authentication call before it gets the feed. In its settings, I have username and password fields in the form. I tried to set the field #type to password, but it seemed not to use the #default_value element, thus obliterating the saved password when you hit the 'save' button.

This maintains the password, but shows it in plaintext:

$form['password'] = array(
  '#type' => 'textfield',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

This shows dots for the password, but does not populate the field using the #default_value, causing you to have to enter the password any time you want to change and save any value on the form:

$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

I need to be able to have the user enter a password and have it stay no matter what other values they change on the form and save. Does this preclude me from using the password field type, since it appears not to use the #default_value element?


texts: What are the CSS classes for block instances?

texts:
Preface

Now in Drupal 8 we can finally create block instances: i.e, placing a block more than once -> in more than one region.

Does any instance has a unique css class?

Why I ask this?

In some cases you want to hide 1 block instance, but not the other.

For example, say you have the block "contact_form" in 2 regions: "Highlighted" && "Sidebar". You can hide the first instance for desktop devices, thus making it appear only for mobile devices this way:

media screen and (min-width: 768px) {

#block-contact-form .instance_1 {display: none}

}

.instance_1 is a fictive name and I used it only to explain how such a class is so needed.
Its .instance_1 and not .instance_2 as In Drupal machine-generated objects are usually Zero-based indexed.

Doing so can be good for better UI-UX and better accessibility for mobile-device users.


texts: Views doesn't recognize a custom handler?

texts:
My Module contains (.module)

/**
* Implementation of hook_views_api
*/
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule') .'/views',
  );
}

and file mymodule.views.inc

function mymodule_views_data_alter(&$data) {
    dpm("viewsdata_alter");
    $data['entity_center']['field_center_verification_code']['field']['handler']="mymodule_handler_field_center_verification_code";
}

and handler class

class mymodule_handler_field_center_verification_code extends views_handler_field {

function render($values) {
    dpm("render");
    dpm($values);
    dpm($this->get_value($values));
    return "test";
 }
}


texts: Put menus into separate file for better handling caching with expires

texts:
I am trying to clear the page cache of drupal as micro invasive as possible by using Cache Expires and custom logic.
On each page, the menu is shown down to Level 2 in a footer and a hover area.
Therefore I did only rebuild all menu trees and remove pages from cache if an item on the second or first menu level has been changes.

Now we have got an additional menu for mobile devices which is load with each page and shows down to four menu levels.
Changing a menu on the first to fourth level would no lead to a clear of almost any pages.

To avoid this, it would be great to put all that menu stuff out of the page html and put in a single file, containing just the menu information in e.g. json format.
So if a menu changes I would only need to update the menu file and the changed node.

Are there any smart hacks out there or even modules dealing with that?


texts: Access rights by cloning a Drupal sandbox repository

texts:
I try to clone a new Drupal sandbox project:

  git clone --branch 8.x-1.x username@git.drupal.org:sandbox/username/projectnumber.git directory

I receive the following error message:

ssh_exchange_identification: read: Connection reset by peer
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

I have the following configuration:

Win8 (64bit)
git 2.11.1 (it is the latest version)
PowerShell / Git Shell / CygWin bash (all display the same error message)

The Troubleshooting does not address the issue.

I have tried several variants of the clone command. The following have worked:

git clone --branch 8.x-1.x https://username@git.drupal.org/sandbox/username/projectnumber.git directory

There are only two chages needed:

https:// before the username
/ instead of : before sandbox

But when I try 'git push', then i get the following error message:

fatal: unable to access 'https://username@git.drupal.org/sandbox/username/projectnumber.git/': The requested URL returned error: 403

If I edit the file .git/config and change the [remote "origin"] url to: ssh://username@git.drupal.org/sandbox/username/projectnumber.git, then I get the same error message as by the clone command:

ssh_exchange_identification: read: Connection reset by peer
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

And if I test the SSH connection: 'ssh username@git.drupal.org', then I get the same error message:

ssh_exchange_identification: read: Connection reset by peer

The error message is the same if I use password or SSH key authentication.

@Jakuje writes:

ssh_exchange_identification: read: Connection reset by peer

You can't establish SSH connection to the remote host for some reason. You are probably blacklisted using /etc/hosts.deny or the server is failing to accept the connections and initiate SSH protocol for other reasons (missing directories, disk failures, full disk, etc.). The logs from the server will tell you more.


texts: How to save dynamic select list value into config table in Drupal 8?

texts:
I wanted to show list of fields per content type in admin config form. After saving the form, selected list value should get save into config table.

public function buildForm(array $form, FormStateInterface $form_state) {
  foreach (node_type_get_types() as $content_type) {
    $entity_type_id = 'node';
    $fields = \Drupal::entityManager()->getFieldDefinitions('node', $content_type->get('type'));
    if ($fields) {
      $options = array();
      foreach ($fields as $field_name => $field_definition) {
        if (!empty($field_definition->getTargetBundle())) {
          $options[$field_name] = $field_definition->getLabel();
        }
      }
      $form['test']['test_' . $content_type->get('type') . '_field'] = array(
        '#type' => 'select',
        '#title' => $content_type->get('name'),
        '#options' => array_merge(array('0' => t('Auto')), $options),
        '#default_value' => $config->get('test_' . $content_type->get('type') . '_field') ? $config->get('test_' . $content_type->get('type') . '_field') : '',
      );
    }
  }
}

Here is submit handler

public function submitForm(array &$form, FormStateInterface $form_state) {

foreach (node_type_get_types() as $content_type) {
  $this->config('test.settings')
  ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field'))
  ->save();
}
parent::submitForm($form, $form_state); }

After saving admin form, test_article_field and test_page_field  is getting saved instead of selected field.

Any help would be appreciated?


texts:
I'm making my first attempt at creating my own Sub-Theme of the Bootstrap theme. I've got the theme installed, the sub-theme created and working, I've added some new regions and populated them. The situation I'm encountering is, the regions just display one under the other, where I want (at least certain ones) to display side by side. I've added "float: left;" code, but that doesn't seem to make any difference. I'm guessing that I need to "float" the region, rather than the block inside of it. However, I'm not sure how to do that. I've searched Google, I've searched YouTube, I've searched Drupal.ORG, I've searched the Drupal Bootstrap site documentation, and I'm not finding anything. Someone on Drupal.ORG told me that such modifications could be made via CSS, however, I've searched the bootstrap-theme.min.css file, and I find no mention of any of the regions. I would appreciate some pointers on how to do this correctly.

I'm using Drupal 8.5.3 and Bootstrap theme version 8.x-3.11


texts: Conference Organizing Distribution (COD)

texts: Is COD shipped as a module or an entire Drupal CMS modified to handle conferencing. I can't find any straight forward documentation installing this to an existing project.


texts:
I have created a custom module that use the ajaxcallbak in form
and i call this module as block inside a external php in root installation

The external file contains the script for calling the bootstrap of Drupal and my custom module :

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

define('DRUPAL_ROOT', getcwd());

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

$block = module_invoke('my_module', 'block_view', 'my_module');
print render($block['content']);

Inside my module i have :

function mymodule_init(){
     global $base_url;

    drupal_add_library('system', 'drupal.ajax');

    drupal_add_library('system', 'jquery.form');

}

function mymodule_form($form, &$form_state) {
  drupal_get_path('module', 'mymodule');
  $form['myfield'] = array(
    '#type' => 'textfield',
    '#size' => 25,
    '#default_value' => '',
    '#required' => false,
   );
    $form['submit'] = array(
    '#type' => 'button',
    '#ajax' => array(
      'callback' => 'ajax_show_result',
      'name' => 'submit2',
      'effect' => 'fade',
      'event' => 'click',
    ),
    '#value' => t('Next'),
    '#attributes' => array('class' => array('btn_suite')),
    );
    return $form;
}

**
* Implementation du hook_block_info().
*/
function mymodule_block_info() {
  $blocks['mymodule'] = array(
    'info' => 'information',
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

/**
 * Implementation du hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();
  switch ($delta) {

  case 'mymodule':
      $block['subject'] = 'subject';
      $block['content'] = drupal_get_form('mymodule_form');
      break;

  }
  return $block;
}

function ajax_show_result($form, $form_state) {
    $mydata= $form_state['values']['myfield'];
    echo $mydata;
}

what am i doing wrong? i'm not able to get the ajax callback firing , my form is always submitted

thanks


texts: How to clear a field using jquery after Ajax form reload

texts:
I have a custom module with a custom form with two fields: field A (select), field B (datepicker). When the user picks field B, it launches an Ajax call to validate field B. All works well so far, except for one issue: if user decides to change field A after the Ajax call, it should clear field B.

My problem is I can't get jQuery to detect that field A was changed after the Ajax is called. I can see field A's id changes from 'foo' to 'foo--2' and I've tried the below code with both '#foo' and '#foo--2' but neither works. jQuery works only the first time the form displays, but not after ajax fires. IOW the user can change field A's selection but jQuery doesn't detect that change, I can't even get the alert to trigger. Any ideas what I might be doing wrong here?

$('#foo--2').change(function(){
    alert ('change detected');
    'input#bar-datepicker-popup-1'.val('');
});


texts:
I had a REST resource for a custom entity working in 8.3, but when I try hitting it in 8.5, I get a 406 with message": "Not acceptable format: json" in the body.

Here's my config, with json clearly defined as the format:

langcode: en
status: true
dependencies:
  module:
    - basic_auth
    - MY_MODULE
    - serialization
id: entity.MY_ENTITY
plugin_id: 'entity:MY_ENTITY'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

I've tried stepping through code with Xdebug in PHPStorm, but not having much luck seeing where this is coming from.


texts:
I created some custom fields for the comment form for specific content types.

One field for instance is the email fields, it's used to contact posts after they won a contest.

But when I look at the comments in the admin, there is no option to view these custom fields.
Is there a way to change this?

So I want to add custom fields to the admin overlay for comments


texts: Template suggestion doesn't work with a custom menu link (custom route)

texts:
In a module I have created a custom link by creating a custom route inside the mymodule.routing.file.yml and the mymodule.links.menu.yml file.
In my theme.theme file I have defined a hook_page_alter to add a template suggestion. With the debug mode and in the html code of the custom page, I see the proposed template suggestions.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
* page--mycustomtemplate.html.twig
x page.html.twig

I have build a new template with this name 'page--mycustomtemplate.html.twig'. After clearing the cache, the new template isn't called, and the default page template is always actived.

Did I forget something?


texts: How to use stye attribute in custom block markup?

texts:
I'm developing a custom block in Drupal 8. In my build() method I've got:

$progress_markup = array(
  '#theme' => 'progress_bar',
  '#percentage' => $registration_percentage,
  '#message' => array('#markup' => $registration_node_count . ' of ' . $this->configuration['capacity']),
);
$markup = \Drupal::theme()->render('progress_bar', $progress_markup);

This generates the following HTML:

%

30 of 120

However, when the block renders on the page, the style attribute has been removed. Here's the relevant D8 issue.

What I don't understand is: if I create a custom block and use Full HTML, and paste in the generated markup that contains the style attribute, Drupal 8 will happily render it. But when I generate this markup in the build() method, it gets removed.

Is there a way to specify, in the block plugin definition, that the build() method should not filter out any HTML? Any other thoughts on how ot get around this issue?


texts: Inquiring about finding mentors in the drupal community

texts:
Recently, I've noticed that drupal.org has added user profile fields for areas such as adding drupal ID's for attributing thanks to some mentors.

I was curious as to see if there currently is a means or process of seeking or finding a drupal mentor online or through drupal.org? I would ask people in person but i really don't know that many drupalers at the current moment.

Would the best place to look be the forums on Drupal.org? Or just persistent begging on IRC? I would eventually like to mentor others myself once i feel comfortable


texts: select term from reference field but deny edit term

texts:
How can I allow users of a particular role select a term from a reference field on a node but deny them to 'edit' the terms from that reference field?

Selecting terms: great.
If, under taxonomy permissions, you tick 'Administer vocabularies and terms' for a particular role, they will see my own created term reference field and they are able to select the term of their preference which is great.

Editing terms: bad.
But if they view the node and see the term, they can click on that term and then they also have the 'edit' permission to edit the term. Surely not what we want because the user might potentially mess up the settings of my carefully designed term reference field.

I'm using taxonomy access control but that only takes care of the node access, not of the term edit access.


texts:
I am using form Api to create a custom form. My form is below.

function myform_form() {
  $form = array();
  $form['name'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#required'      => FALSE,
    '#weight'        => 2,
  );
   $form['telephone'] = array(
    '#type'          => 'textfield',
    '#title'         => t(''),
    '#weight' => 3,
    );
     $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
     );
  return $form;
}

function myform_submit($form, &$form_state) {
  drupal_set_message(t('Your form has been submitted successfully.'));
  $form_state['redirect'] = 'thankyou';
}

I used to show this form in lightbox as this :

 Form

Form is correctly showing in lighbox. But when i submit the form it opens the thankyou page in popup.

I used

 Form

It closes the popup event if form validation returns false. I don't want to close the popup if there is any validation error. I added this to myform_submit function :

parent.Lightbox.end();

But drupal_add_js is not working in myform_submit function.

Updated :

I send a parameter to thank you page and added this on the page load.

<?php if($_GET['redirect']) { ?>

<?php } ?>

Its redirecting but it shows content in popup for few seconds and redirect after that. I don't want to display popup for a second also after submitting the form.


texts: How do i hide a views field(button) based on rolde?

texts: I have a question, I have created one custom button by altering the view and now i want to restrict that button for few roles like for role 1 & role 3 it should visible but for role 2 & role 4 it should not visible. please help me how to do this...?


texts: How do I configure the migrate API to assign all parent and child taxonomy terms to an entity during import?

texts:
I'm importing media files which have a taxonomy in the media content type definition.

Here is the section of my Yaml file that deals with the taxonomy.

field_nih_asset_taxonomy_auto:
    -
      plugin: skip_on_empty
      method: process
      source: nihtaxonomy
    -
      plugin: hierarchical_taxonomy
      bundle: nih_asset_taxonomy_auto
      ignore_case: true
      source:
        - t1
        - t2
        - t3
        - t4
        - t5
        - t6
    -
      plugin: explode
      delimiter: /

The second plugin 'hierarchictal_taxonomy' comes from the Migrate Hierarchictal Taxonomy module.

My source file is a json file and here are the mappings for the two plugin sources from above.

"nihtaxonomy": "ntp-db/ntp_reports/ntp_pathology_tbls/99020_tables",
"t1": "ntp-db",
"t2": "ntp_reports",
"t3": "ntp_pathology_tbls",
"t4": "99020_tables",
"t5": "",
"t6": ""

What I'm expecting to happen is the import reads from the 'nihtaxonomy' source, explodes that, and assigns all of those terms as taxonomies.

Then, I'm expecting the hierarchical taxonomy plugin to create the parent child relationships. (there are no more than 6 terms, but it varies per record, if that matters).

This is working correctly. The problem is that the only term that's being assigned to the entity is the last child, so 99020_tables in this example. But I need all of the terms attached.

How do I need to configure my Yaml file so all the terms get attached to the node?


texts:
I'm new to Drupal (having used Perch CMS and PHP for years). Forgive me if I bumble the terminology a bit. I've been furiously going over documentation and tutorials. Sorry in advanced for being verbose.
Using Drupal 9 with a Bootstrap 5 template I'm developing -  I'm looking to create a page that has a listing of downloadable PDFs that are categorized into groups and subgroups - these will eventually be placed in nested accordions on a page:
DOCUMENT LIBRARY
== Category A
==== Sub Category AA
====== Content: Has title, image and file link
==== Sub Category AB
====== Content: Has title, image and file link
== Category B
==== Sub Category BA
====== Content: Has title, image and file link
====== Content: Has title, image and file link
==== Sub Category BB
What I've done so far: I've setup a vocabulary tree that matches the structure I need. I also created a content type that meets the needs of each content item and have added taxonomy to the content form display. Created a view that show the content type.
What I need to do: Cycle through the taxonomy tree structure to create the accordions, showing the taxonomy term name and then nest each content item that matches the taxonomy term.
What I need from the community: Make sure I'm going down the right path and that I'm not misusing Drupal in this way. Also, any tips and/or things I should search for would be helpful. I'm pretty comfortable with theming (twig).


texts: Any module or way to add line item in existing order?

texts:
Is there any way so that admin or whoever permission can add the line item in existing order while editing the order?

Any module or custom code?


texts: How to stop a local database from launching the online website?

texts:
I'm a designer and new to Drupal. been studying for a couple of months creating sites for personal learning. I started working in a company that had a Drupal 7 website. I studied, learned it and change it.

This year a Design Studio redesign our image and made a Drupal 8 site. They gave me full access and I downloaded a copy of the files and the database and proceed to install it locally to test and change it.

I use Acquia DevDesktop and import the site with new database and the I went into phpMyAdmin and import the database. Then I load the site and it immediately launch the real online site.

I thought there was something in the files and check them extensively with the little knowledge that I have. I found nothing.

To check if the "reroute" was in the files I made a fresh install of Drupal 8 and after setting it up as a new site I went into phpMyAdmin and import the database. Without changing any file I launched the site and again it went in to the real online site. So I thing the "reroute" is in the database.

I called the Design Studio and the responsible for the site was a Designer. He created the site online and didn't managed it locally. He try to help me but was unable to pinpoint the reason for the local installation to go to the real online site. He couldn't set up the site locally either.

How to change this "reroute" so I can set up my site locally?


texts:
Is there a documented date, or a believed date for the end of life of Drupal 6?
In other words, when will official development stop on Drupal 6?


texts: Drupal 7: Add markup to form during validation

texts:
I have a custom validator on a webform. When a person enters an address, I validate it. When the address is not right, I set an error in the validation function. This is all going well. But now I want to give the visitor suggestions when he enter a wrong address. This should be done by giving the suggestion in a markup underneath the address input.

I allready set up an empty markup field in the webform, now I just want to put information in it during validation. How is this possible. If you need any dpm or printout let me know please.

Thanks in advance.


texts: Different styling for each teaser display

texts:
How to style Teasers differently in different displays and pages?

I am struggling very much with Drupal's CSS classes for teasers....Is there anyway to add them separate class name for each case?

Now, if I'm styling Teasers on Taxonomy page - the same class applies to Teasers on Front Page Promoted teasers, in Teaser blocks in Views, etc....

Well, I removed "promoted" teasers and put them in Views block and assigned a class; and it's separate on Taxonomy page....

BUT - what would I do if I would wish to have a separate template on some other (taxonomy) page for...teasers?

All those Teasers are in one big pot, named .node-teaser and the same field names...

//Using D7 and Zen 7.x.5x.


texts: How to make my custom theme suggestion the most specific

texts:
Is it possible to guarantee my custom theme suggestion is at the top of the list for theme suggestions? Something like the following

<!-- FILE NAME SUGGESTIONS:
  x my-custom-theme-suggestion.html.twig
  x input--textfield.html.twig  // ALSO WHY DO I HAVE TWO OF THESE
  x input--textfield.html.twig
  * input.html.twig
-->

Also I'm not sure why but I have two theme suggestions that are the same. Anyone else experience that?


texts: Show a menu block only on nodes that belongs to this menu

texts:
I am trying to accomplish something similar to the book navigation module.

Say I create a block containing a menu. I want this block to become visible for nodes that belong to this menu.

So if NodeA belongs to the menu "My SubMenu 1", which is included in a block called "My Submenu 1 Block", I want this block to appear everytime NodeA comes up.

This could be accomplished with some pathauto tricks, or assigning a certain taxonomy term to all nodes of "My Submenu 1". But I realise this is redundunt, there is no need to force the user to create content with specific terms--the information is all there in menu-->node connection.


texts:
I need to create an XML page. I created a page with my custom module, and I tried to display it, but it showed as a normal Drupal page with blocks.

function my_custom_function_name_xml_list() {
  $output = '<?xml version="1.0" encoding="UTF-8">';

  return $output;
}

How do I avoid Drupal adds its own content to the output of my function?


texts: What does "sanitized" mean (in api documentation)?

texts:
Hi
I see the word "sanitized" quite often in Drupal API documentation.

For example, this page: theme_username($variables)

  $variables An associative array containing:

  account: The user object to format.

  name: The user's name, sanitized.

  extra: Additional text to append to the user's name, sanitized.

What does sanitized mean in the context?


texts: Drupal behaviour function not getting executed

texts:
I defined a simple block on my module, using the following code.

function visita_virtual_block_view($delta = '') {
  switch ($delta) {
    case 'mapa':
      $path = drupal_get_path('module','visita_virtual');
      drupal_add_js('https://maps.google.com/maps/api/js?sensor=false','external');
      drupal_add_js($path.'/visitavirtual.js');
      $block['subject'] = t('google maps');
      $block['content'] = visita_virtual_mapa_content();
      return $block;
  }
}

That returns a simple div with an specific id, wich will allow me to alter it later through the usage of the google maps api.
For that I defined my 'visitavirtual.js' file, and inside of it I declared the Drupal behavior. That function is supposed to get executed when the whole page is loaded, since it'as a wrapper of the JQuery ready function.

(function($){
  Drupal.behaviours.visita_virtual = {
    attach: function(context,settings) {
      alert('Entered the init function');
      var latlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    }
  };
})(JQuery);

However, that code is not executed; I can't even see the alert window. What am I doing wrong?


texts:
I did this in my custom module:

/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return [
    'my_module' => [
      'template' => 'my-module'
    ],
  ];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 *
 * @param array $suggestions
 * @param array $variables
 */
function my_module_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Block suggestion for specific block bundle.
  if (isset($variables['elements']['content']['#block_content'])) {
    $block_bundle = $variables['elements']['content']['#block_content']->bundle();

    if ($block_bundle = 'my_block_bundle') {
      array_splice($suggestions, 1, 0, 'my_module');
    }
  }
}

I already created this block bundle in the module, so I want to use my template from module (my-module.html.twig in my_module/templates) for all blocks in this bundle, but with this code all my blocks in this bundle disappeared.

What I'm doing wrong here?


texts:
I have created a views block and page to display nodes based on term of a taxonomy vocabulary (contextual filter).
From this block I have a more link enabled and linked to the page.
Here how to make the views page path linked to corresponding taxonomy term pages?


texts: What kind of hook_entity can be trigerred by a migration on this entity?

texts:
I have a custom content entity on which I can run a dedicated migration from csv with a form.
The form is used to

upload the csv file
launch the migration

The submit part of the form:

  $fileId = $form_state->getValue('file_to_import')[0];
  $file = file_load($fileId);
  $uri = $file->uri->value;
  $filename = $file->filename->value;
  $filenamenew = 'migration_UpdateMembers.csv';
  $urinew = 'private://migration_UpdateMembers.csv';
  $file->setFilename($filenamenew);
  $file->setFileUri($urinew);
  $file->save();
  rename($uri, $urinew);

  $migration_id = 'migration_updatemembers';
  $migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
  $executable = new MigrateExecutable($migration, new MigrateMessage());
  $executable->import();

The corresponding Migration .yaml is:

id: migration_updatemembers
migration_tags: null
migration_group: null
label: 'Update Member from CSV'
source:
  plugin: csv
  track_changes: true
  path: sites/default/files/_private/migration_UpdateMembers.csv
  delimiter: ';'
  header_row_count: 1
  ids:
    - id
process:
  id: id
  status: status
  enddate: enddate
destination:
  plugin: 'entity:member'
migration_dependencies:
  required: {}
  optional: {}

I assumed that, as the migration updates the entity content, hook__entity_update would be fired. And it is not! Not as I expected...
Here is my hook__entity_update:

function association_entity_update(EntityInterface $entity)
{
ksm($entity);
  $mode = 'update';
  switch ($entity->getEntityType()->id()) {
    case "member":
      break;
    case "person":
      break;
    default:
  }
}

As far as I understand the result of ksm see below), it seems that it is the $file->save(); that triggers the hook. And it fires only once. Not for any 'member' update...


texts: Similar Products don´t get grouped on review Page

texts:
When adding multiply quantities of the same product they don´t get grouped but splitted to each line on the overview checkout pane.

-Example-

Instead of:

  Product: PLAYSTATION QTY 3

It shows:

  Product: PLAYSTATION QTY 1

  Product: PLAYSTATION QTY 1

  Product: PLAYSTATION QTY 1

I know this is a view, I tried to configure it to grouping, but with no change.
Even this module did not help:
https://www.drupal.org/project/views_aggregator

What can I do to have all similar products grouped and sum quantity?


texts: How do I get clean output with indented structure

texts:
How can I create a clean theming markup so that the output uses the same indented structure as in my static html template? E.g. when I insert $head;  Drupal uses it’s indenting format.

How can I control the ouput?

snippet from the html.tpl.php

<head>

  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>

</head>

The output looks like this

<head>

  <title>Lorem Ipsum | mothership</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Generator" content="Drupal Mothership" />
<link rel="canonical" href="/d7-demo/node/1" />
<link rel="shortlink" href="/d7-demo/node/1" />
  <style media="screen">
@import url("http://localhost/d7-demo/modules/shortcut/shortcut.css?nmdogy");
@import url("http://localhost/d7-demo/modules/toolbar/toolbar.css?nmdogy");
@import url("http://localhost/d7-demo/sites/all/themes/mothership/mothership/css/mothership.css?nmdogy");
@import url("http://localhost/d7-demo/sites/all/themes/itsgoodtobehere/bootstrap/css/bootstrap.min.css?nmdogy");
</style>

</head>

instead of

<head>

  <title>Lorem Ipsum | mothership</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="Generator" content="Drupal Mothership" />
  <link rel="canonical" href="/d7-demo/node/1" />
  <link rel="shortlink" href="/d7-demo/node/1" />
  <style media="screen">
    @import url("http://localhost/d7-demo/modules/shortcut/shortcut.css?nmdogy");
    @import url("http://localhost/d7-demo/modules/toolbar/toolbar.css?nmdogy");
    @import url("http://localhost/d7-demo/sites/all/themes/mothership/mothership/css/mothership.css?nmdogy");
  </style>

</head>


texts: I'm trying to set the fotorama jQuery slider to use a local image file path rather than an external web link as I'd like to put a .htaccess on these to prevent hotlinking to them, however, when I do this (put .htaccess on them), it prevents my image sliders from working and I can't seem to find a way to get a local file path to work. I was wondering how I can use a local file path with fotorama? I am using Drupal 7. Thanks.


texts:
I'm using https://github.com/drupal-composer/drupal-project to install Drupal 8. The only thing I've changed in the composer.json is to freeze Drupal core version to 8.8.1

After Drupal installation I get WSOD and see the following errors in PHP logs:

Uncaught PHP Exception InvalidArgumentException: "Class "\Drupal\system\Controller\Http4xxController" does not exist." at /var/www/html/web/core/lib/Drupal/Core/DependencyInjection/ClassResolver.php line 24
Uncaught PHP Exception InvalidArgumentException: "No check has been registered for access_check.permission" at /var/www/html/web/core/lib/Drupal/Core/Access/CheckProvider.php line 97

Happens on PHP 7.2 and 7.3

UPD: this issue does not happen with Drupal 8.8.0

UPD2: This issue happens regardless of whether you freeze drupal core or not. Also happens with the (now) official composer template drupal/recommended-project. This issue happens only during installation from web, if you install via CLI it doesn't happen. There's an issue now in the official Drupal tracker https://www.drupal.org/project/drupal/issues/3103529. P.S.: I don't know why someone decided to close this issue as not relevant to Drupal. This is the Drupal core issue. I tried to reopen a couple of times but my request was ignored.


texts: i want to select elements that exist on table_A and not in table_b, in other words, how to make the sql "intersect" in a drupal select query please ?


texts:
I am trying to fix something that was done from a previous developer who used the Books Module in Drupal 7. I can't figure out how to change the link to return to the parent "chapter" as seen below. The link is wrong and I just need to change it. I'm just not sure where that info is stored.

How is that menu created? I've already looked and he did not use the Book Navigation Block.

Update: I think I found a template file that contains the code, but I'm still not sure how to alter it or fix this link:

<?php print l('‹ All Chapters in this Program', drupal_get_path_alias('node/' . $parent_node->nid), array('class' => 'font_15')); ?>


texts: Drupal commerce change quantity textfield in cart view to selectbox

texts: Is there a way to change the quantity widget in the Drupal Commerce cart view from a textfield to a selectbox? And then refresh the page when the selectbox is changed without making the user press the Update cart button?


texts: Exposed filters and contextual taxonomy description

texts:
A view called "Music".

Fields: "title", "image"
Exposed filter: "category" (is a taxonomy-field = rock, jazz, salsa,...).
Every taxonomy-term has a description.

When the visitor for example, selects "rock" the results are filtered.
So far, so good.

But i want also want that when a "category" is selected, the description of the selected term is displayed above the results.

I think that could be done with an attachment and contextual filters, but i can't get it working.


texts: Using a select form field for the field that selects the groups where a node is posted

texts:
The form for creating a node for the content type that has been set as content type for the Organic Groups module has checkboxes for choosing the groups where a node is posted; I want to use a select form field instead of the checkboxes.

How should I alter the form field?

I have tried some patches from drupal.org, but they do not works correctly.

I have used the following code.

/**
 * Helper function; Make the groups audience accept only a single group.
 */
function og_single_group_form_alter(&$form, $form_state, $form_id) {
  if (module_exists('og_access')) {
    $path = drupal_get_path('module', 'og_single_group');
    drupal_add_js($path . '/og_single_group_hideoption.js');
  }

  if (!empty($form['og_nodeapi']['visible']['og_groups']) && ($form['og_nodeapi']['visible']['og_groups']['#type'] != 'value')) {
    $options = array();
    $options = array(t('Personal blog')) + $form['og_nodeapi']['visible']['og_groups']['#options'];
    $form['og_nodeapi']['visible']['og_groups']['#type'] = 'select';
    $form['og_nodeapi']['visible']['og_groups']['#multiple'] = FALSE;
    $form['og_nodeapi']['visible']['og_groups']['#options'] = $options;
    // Add own submit handler so we can cast the groups back to an array.
    $form['#submit'][] = 'og_single_group_submit';
  }
}

 /**
  * Submit handler; Since we permit only a single group per content, we need to
  * case to groups into an array
  */
function og_single_group_submit($form, &$form_state) {
   if (!empty($form_state['values']['og_groups']) && !is_array($form_state['values']['og_groups'])) {
     $form_state['values']['og_groups'] = drupal_map_assoc((array)$form_state['values']['og_groups']);
   }
  else if (empty($form_state['values']['og_groups'])) {
    $form_state['values']['og_groups'] = array();
  }
}

The code causes the following error:

  Warning: array_filter() [function.array-filter]: The first argument should be an array in /var/www/mysite/sites/all/modules/contrib/og/og.module on line 1303.


texts: How do you rename the machine name of a content type?

texts:
I have this content-type that i created titled: "Engineering".
1500 hundred nodes later management wants me to rename it : "Staff". I can easily rename the label but how do i rename the machine name? Does anyone have any success renaming a content-type machine name that is loaded with content/revision and relationships?
It is sometimes impossible to predict these kind of changes. How do we rename the machine name a a content-type.
i have tried the instructions from this article below : https://medium.com/@philw_/how-to-change-a-content-type-s-machine-name-in-drupal-8-33fc3c0520dc with no success.

Error: bundle name cannot be changed.

I will be trying the following:
export the database out.
find and replace the old content-type machine name with the new name
I will also rename any tables named after the content type in the process
re-import the db
I will see how that works out.


texts: How to restrict field permissions to referenced user?

texts:
I have a submit-review process where submitters choose their reviewer. The reviewers are linked By User Reference module. Submissions are public but have an Accept/Deny review button implemented with Button Field which only should be accessible by referenced user.

Workflow fields submodule seems to accomplish that behavior but unfortunately I can't get it to work with Workflow. There is an incompatibility of versions and maintenance seems not to be very active.

So I try to build my own solution using hook_field_access() like that:

function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && ($field['field_name'] == 'field_accept_review' || $field['field_name'] == 'field_decline_review')) {
        // is current user == node reviewer?
        return ($entity->field_reviewer == $user->uid);
    }
}

Do I have to use user_load() before getting to the uid of the linked user?


texts: Commerce: how can I execute javascript after a product has been added to the cart?

texts:
I want to run Javscript once a product has been added to cart (with the script including product info).

The only thing I have tried is hook_commerce_cart_product_add() with drupal_add_js() but this doesn't seem to work. Ideally I would like it work like drupal_set_message(), so the script displays on the next page view.

I also need to get this working with removing products from the cart.

EDIT: Well I've discovered that doing the following actually works, but seems dodgy as hell, and would like to find a better way:

drupal_set_message("<script>alert('TEST');</script>");

Any ideas would be welcomed!


texts:
I am trying to make my own theme for drupal 8. but I am struggling with the menu.
my menu looks something like this

parent1
- child 1.1
- child 1.2
parent2
- child 2.1
- child 2.2

but only the parents are visible.

I used the menu.html.twig file from the classy theme.

edit:
I tried my theme on other site and there the children are displayed. so guess the problems was not because of theme. so i activated the stark theme, but also there I can't see my full menu tree.
and the checkboxes show as expanded are checked


texts:
I'm using Adaptivetheme with the pixture_reloaded sub-theme. Keep in mind, it's structured as:

Adaptivetheme
  -Adaptivetheme_Subtheme
      -Pixture_Reloaded

I'm creating custom edits to template.php to add a node preprocess which creates a custom variable for me, and then editing node.tpl.php to add my variable to the output.

Editing adaptivetheme_subtheme node.tpl.php and adaptivetheme_subtheme node preprocessor gives me the output I want. I understand that the best practice is to edit the sub-theme files...

In my case is the "sub-theme files" the adaptivetheme_subtheme files or the pixture_reloaded files?

Pixture_reloaded itself doesn't have a node.tpl.php file, so I've tried copying both the one from adaptivetheme and adaptivetheme_subtheme to the pixture_reloaded directory, but it's like it never reads the file.

EDIT:

  Pixture_reloaded itself doesn't have a node.tpl.php file, so I've
  tried copying both the one from adaptivetheme and
  adaptivetheme_subtheme to the pixture_reloaded directory...

I had shutdown my server yesterday, and after bringing it back up, my output was correct.

I had cleared out the cache in the backend of the site... shouldn't that have done it for me?


texts:
I'm looking for a way (simple) for my editor to save a draft version of an already published node to a later date.

So in other word a way to publish changes on a later date!

Having the possibility to have more than one version on bank would be nice.

Thanks!


texts: How would I insert one item into the user-edit page with templates?

texts:
I'm looking to insert a button into the user edit page. I've seen examples of how to edit the entirety of the user-edit page, but I want to keep everything intact and only make one small change.

Is it possible to do this without building the entire user-edit page all over again from scratch?


texts: How can execute batch api over cron jobs

texts:
I am working on Drupal 8 and batch API. I created the batch api calling importingmatch and it should automatically importing every 1 hour.

My solution is use Drush for make it works without the browser, but I don't know how I can get the batch id.

Here is my code about the Batch API:

// Set up the Batch API
    $batch = array(
        'operations' => $operations,
        'finished' => 'importingmatch_finishedBatch',
        'title' => t('Import match'),
        'init_message' => t('Starting import match.....'),
        'progress_message' => t('Completed @current step of @total.'),
        'error_message' => t('Import match deletion has encountered an error.'),
    );

    batch_set($batch);

Currently, this batch is runing perfect if I access from my PC. Url: www.mysite.com/importing_match
I am not sure how make it working from the server Centos with Drush, I need the batch ID for execute: Drush batch-process

UPDATE:
- Interesting with the Command for Drush, I created custom Command from my module. Following from here: https://www.chapterthree.com/blog/how-to-create-custom-drush-commands. But it's still not working, it's showing:

The drush command '<name>' could not be found.

I changed from localhost to 127.0.0.1 from the settings.php but it's not helpful. Any idea?


texts: Webform component: Loses value after validation

texts: I have a webform component. When submitting (without filling in required fields), I get error messages, but the value of that component disappears. How should the value be retained?


texts:
What causes Drupal 5 to run a cron job?

I know about cron.php.  Are there any other ways in which cron is likely to be called?  For instance are there any core or commonly used modules that call it?


texts: Programmatically set class on extended field type

texts:
Earlier I created an extended version of the Node class. I called it AbleNode and it extended BaseNode. In order to set all nodes to this node type I added this to my custom .module file

function ablecore_entity_type_build(&$entity_types){
    if(isset($entity_types['node'])){
        $entity_types['node']->setClass('Drupal\ablecore\Plugin\Node\AbleNode');
    }
}

This works fine but I'm not sure how to do this with an extended field type. Here is the code for my field class that is extending the BaseFileFieldItemList class

<?php
namespace Drupal\ablecore\Plugin\Field\FieldType\FileFieldItemList;
/**
 * @file AbleNode.php
 */
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList as BaseFileFieldItemList;

class AbleFileFieldItemList extends BaseFileFieldItemList {
    public function style($image_style) {
        $image_style = \Drupal\image\Entity\ImageStyle::load($image_style);
        if (!empty($image_style)) {
            return $image_style->buildUrl($this->getEntity()->getFileuri());
        } else {
            return false;
        }
    }
}

I see how I was able to turn all nodes into AbleNodes, but I'm not sure how to make all FileFieldItemLists into AbleFileFieldItemLists. Is there a hook I can use to setClass on the field whenever I encounter it? Keep in mind that I'm not trying to create a brand new field, I just want to give more functionality to existing field types.


texts: How to use mmenu without breaking core Overlay

texts:
How can I use mmenu jquery library without breaking core Overlay. Overlay works, but when I do a page refresh (F5) the overlay is blank. When I prevent the mmenu library from loading it works again.

I load the library in hook_preprocess_html in my custom zen theme:

drupal_add_css(drupal_get_path('theme', 'zen_sub') . '/css/mmenu/jquery.mmenu.all.css');
drupal_add_js(drupal_get_path('theme', 'zen_sub') . '/js/mmenu/jquery.mmenu.min.all.js', 'file');
drupal_add_js(drupal_get_path('theme', 'zen_sub') . '/js/zensub.js', 'file');

I then add the menu to the zen theme in hook_preprocess_page through a preprocess variable:

$menu_left = menu_tree_all_data('main-menu');
$menu_left = menu_tree_output($menu_left);
$menu_left = drupal_render($menu_left);
$vars['mmenu_markup'] = array(
      '#markup' =>
        '
' . $menu_left . '
',
);

And finally I include placeholders for the menu, as well as the preprocess variable in my page.tpl.php

 <?php print variable_get('site_name', "ZenSub");?>

<?php print render($mmenu_markup); ?>

And Finally this is my js file (zensub.js) to set it all in motion:

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.zensub = {
        attach: function(context, settings) {
            $('div#menu-left').once().mmenu({
               offCanvas: {
                   position: "left",
                   zposition: "front"
               },
               header   : true
            }, {
                // configuration object
               classNames: {selected: "active"}
            });

        }
    };

})(jQuery, Drupal, this, this.document);


texts:
I'm using geolocation field.

I'm trying to limit the zoom out on a leaflet map.

There is the "minzoom" option with leaflet, but the option is obviously not offered by the module.

Do you know what solution is there?


texts: How can I allow/facilitate users to upload images and create a slideshow?

texts:
I want the users of my page (who will not be especially technical) to be able to upload multiple images which other users can comment on etc.

I'm thinking of using the Drupal core module 'book' to create the parent page, which would display the images stored in its children.

Is it possible to do this dynamically so that the users do not have to create a new content type for each of the slideshows?


texts:
My initial installation of Drush couldn't even recognize commands such as "drush migrate-status", therefore I reinstalled drush and followed the steps in the included README.

After reinstallation, drush now recognizes the command "drush migrate-status", hwoever it is throwing an error and crashing. I am confused as I have not even enabled the migrate_example module included with the Migrate module, however drush is throwing the error message below:

require_once(/var/www/drupal7/sites/all/modules/migrate_example/beer.inc):[warning]
failed to open stream: No such file or directory bootstrap.inc:3024
PHP Fatal error:  require_once(): Failed opening required '/var/www/drupal7/sites/all/modules/migrate_example/beer.inc' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/drupal7/includes/bootstrap.inc on line 3024
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: require_once(): Failed opening required
'/var/www/drupal7/sites/all/modules/migrate_example/beer.inc'
(include_path='.:/usr/share/php:/usr/share/pear') in
/var/www/drupal7/includes/bootstrap.inc, line 3024

This all seems very cryptic to me, especially when I have not enabled the migrate_example module and I have the migrate_example directory under migrate.

Could someone please explain why drush might be throwing this error?


texts: Translate a JS string from interface translations doesn't work

texts:
I've a problem about string translations.

I've built a multi-language site and in a custom module, in a JS file, I've used the function t() to make translatable some strings. These strings appear in /admin/config/regional/translate and I'm able to edit their value, but then, after cleared cache when I visit the site I see the strings not translated.

The strangest things is that for other elements the system works. I'm not able to debug this, my apache error and access logs are clear, nothing also in the message log of Drupal.

Anyone can help me?
Thank u in advance


texts: Get a field setting in hook_form_alter()

texts:
Is it possible to get all fields of a specific type in hook_form_alter?

By fields I mean an array of something that contains each fields name and settings.

The reason why I want it in hook_form_alter is that I need to add a property to the form tag that depends on field setting, using $form['#attributes'].

Is there another/better way of doing this?


texts: which page/code renders admin/config in drupal 7

texts: I have a very basic question. In my drupal 7 installation when I go to admin/config the page does not render and all I get is a 1 printed out. I am sure someone die a die() on this page. But I am not sure which page is loaded when admin/config is rendered. Can anyone point me which possible page/code I should be looking at?


texts: Is it possible to create a custom theme function?

texts:
I want for example to create a mytheme_table function to override theme_table etc. (in template.php) but I do not want to use it everywhere in my project.

I need to replace the table with a div or to remove some hardcoded wrappers.

$output .= theme('table_custom', array('header' => $header, 'rows' =>
$rows, 'attributes' => array('id' => $table_id, 'class' =>
array('field-multiple-table'))));


texts: Having duplicate entry error with Panelizer module

texts:
I installed the Panelizer module and enabled it for a specific content type. When trying to add new content, I get a duplicate entry error as follows :

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry 'node-196-197-page_manager' for key 'PRIMARY': INSERT
  INTO {panelizer_entity} (entity_type, entity_id, revision_id,
  no_blocks, css_id, pipeline, did, view_mode, css_class, title_element,
  link_to_entity) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 196
  [:db_insert_placeholder_2] => 197 [:db_insert_placeholder_3] => 0
  [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => standard
  [:db_insert_placeholder_6] => 0 [:db_insert_placeholder_7] =>
  page_manager [:db_insert_placeholder_8] => [:db_insert_placeholder_9]
  => H2 [:db_insert_placeholder_10] => 1 ) in drupal_write_record() (line 6888 of
  /Library/WebServer/Documents/www/jkl/includes/common.inc).

Any insight?


texts: How to completely remove Drupal from system to start over!

texts: I am an apprentice and am using Drupal for work it installed Drupal on to my machine and got it all up and running then I accidently logged out and now I can't log back in. I have tried to send a password reset but Drupal doesn't like the email address or username that I put in. I'm relatively new to this so I ask to keep it simple! :) What can I do?? Thanks in advance


texts: How can i allow users to give different responses to content types other than comments? for example if i want users to be able give blog posts a "like" or "thumbs up/down" or something similar?


texts: How and where does drupal call Drupal.behaviors.password attach method?

texts:
I am experiencing a bug in my setup. The symptom is, that the translate variable in Drupal.behaviors.password in core module user/user.js populated from the passed in settings (settings.password) is undefined and hence the password strength checker is not displayed. Whats worse, is that any other javascript on the user edit page for instance fails due to the javascript error.

Can anyone point me in the direction as to where drupal actually calls the Drupal.behaviors.password.attach?

Thanks in advance.


texts: How to create a Content Type that reuses data from existing Content Type?

texts:
I have a specific use case that does not seem to be covered by existing Drupal 7 modules. I need to be able to create a "content type" that is created by choosing from a list of existing content.

Use Case:
A company that trains new pilots needs two content types:
Type 1: Schedule a training flight.
Type 2: Post training flight details.

Type 1 has the following fields:
(flight_id,trainer_name, plane_name, new_pilot_name, date, airport, flight_status)

IMPORTANT:
Type 2 is created when an admin clicks on the flight_id from a list of scheduled flights.

Type 2 is required to contain the following data/fields:
(content from type 1, trainer_notes, new_pilot_grade)


texts: Migrate file field paths not the actual file

texts:
Say I drag and drop files from a source site into the folder structure of a new site (destination site) that I'm migrating content to. The source sites file paths are the exact same as the destinations paths.

Source:      sites/default/files/attachments

Destination: sites/default/files/attachments

So instead of migrating the actual file I just need Drupal to point to the same location as the source site and the file will be there but when migrating the files over it wants to migrate the entire file.

Is this possible? Maybe after content migration I will need to reconfigure the attachments paths?


texts: How to incorporate AMP in an existing theme?

texts: Is there a way to incorporate AMP into my Porto Theme?


texts:
Is it possible to add external javascripts directly into the .info file of a theme?
e.g scripts[] = http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js


texts:
I can't find a Drupal API function in D7 that tells me if an (unmanaged) file exists.
D6 had a file_check_location but not for 7.

How to check if (unmanaged) file exists?


texts: Pass book node id as second parameter to drupal_block("book_navigation")?

texts:
I'm trying to use drupal_block("book_navigation") in a twig template (with the twig_tweak module installed) to display a list of chapters for a book page. But I'm getting a list of all books and their chapters.

Is there a way to use drupal_block("book_navigation") to produce a list of chapters for just the one book, maybe by passing the id of the book node as a second parameter? Or some other way?

Compare to the user interface /admin/structure/block. There, when you place a Book Navigation block in a region, you can choose the configuration option "Show block only on book pages". This causes the block to produce a list of chapters for only the book whose page the list appears on. So it's clearly possible to do it using the book navigation block. Just need to know how.


texts: Disable browser auto-complete/auto-fill for username and password form fields?

texts:
I have a custom username and password field in my form which is independent from the normal website login.

public function getFormFieldUsername() {
  return [
      '#type' => 'textfield',
      '#title' => 'Username *',
      '#attributes' => ['autocomplete' => 'off'],
    ];
  }

  public function getFormFieldPassword() {
    return [
      '#type' => 'password',
      '#title' => 'Password *',
      '#attributes' => ['autocomplete' => 'off'],
    ];
  }

The '#attributes' => ['autocomplete' => 'off'], doesn't block the auto-fill from the browser tho. Is there a way to achieve that anyways?


texts: How to move blog to a custom path in drupal?

texts:
I want to move default blogs to a custom URL
i.e. blog are by default present at ./blog  but i want them to be at ./share/blog I don't want to use url aliases. I want a permanent move.


texts:
I have a "Buildings" content type. Within that content type I have a building_id field, which contains the building ID.

I have an "Employee" content type. Within that content type I have an entity reference to the Buildings content type.

I have a CSV file for employees but it does not have the building label or the node id, only the building_id.

So my issue is that when I run the employee feed import, I cannot add the building since I only have the building_id.

How would I map the building_id in my csv to match the building_id in the building content type so that it knows which building node it is referencing?

I hope that makes sense :)

Thanks!


texts: How to get rid of Deadlocks and Lock time out type issues?

texts:
I read multiple blogs, tried to google, it but didn't find any satisfaction from any solution. I have the following issues :

PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction: DELETE FROM {cache_field} WHERE (cid LIKE :db_condition_placeholder_0 ESCAPE '\\') ; Array ( [:db_condition_placeholder_0] => field\_info:% ) in cache_clear_all() (line 163 of \includes\cache.inc).

PDOException: SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: SELECT 1 AS expression FROM {sessions} sessions WHERE ( (sid = :db_condition_placeholder_0) AND (ssid = :db_condition_placeholder_1) )

I tried to solve this by increasing innodb_pool_buffer_size and wait_timeout in my.ini but didn't worked.

I changed my cache table's engine from Innodb to MyIasm. The issue gone but it is not a perfect solution. The table engine will be changed after an upgrade of drupal. This issue doesn't affect anything on the site but I don't want this to occur.

Any solution guys?


texts: Webform field default value + Profile field value

texts:
I have a simple Webform (https://www.drupal.org/project/webform):

Single field called "name".

I also have a Profile (https://www.drupal.org/project/profile):

Profile is called "basic_profile".
Profile contains 2 fields: "field_name" and "field_department".

I want the default value of my Webform field "name" to be the content of the user's Basic Profile value for "field_name", but I cannot save the form because "Default value is using the following invalid tokens".

I have also tried using "[webform-authenticated-user:display-name]" which does not work.

I have tried using "[current-user:display-name]" which works but does not give me the info I want.

So how can I get the user's profile values to be used as default values for form fields? Thanks!

P.S.: The reason for this is that we are authenticating via Active Directory, and Drupal will be loading a user's profile from AD upon login. Therefore we want to leverage all data that exists in AD.

composer.json:

{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/adminimal_admin_toolbar": "^1.5",
        "drupal/adminimal_theme": "^1.3",
        "drupal/business": "^1.7",
        "drupal/business_responsive_theme": "^1.1",
        "drupal/console": "^1.0.2",
        "drupal/core": "~8.5",
        "drupal/devel": "^1.2",
        "drupal/domain": "^1.0@alpha",
        "drupal/domain_theme_switch": "^1.3",
        "drupal/eform": "1.x-dev",
        "drupal/honeypot": "^1.27",
        "drupal/insert": "^1.0",
        "drupal/maestro": "^2.1@RC",
        "drupal/mailsystem": "^4.1",
        "drupal/metatag": "^1.4",
        "drupal/module_filter": "^3.1",
        "drupal/paragraphs": "^1.2",
        "drupal/pathauto": "^1.1",
        "drupal/profile": "^1.0@RC",
        "drupal/token": "^1.3",
        "drupal/webform": "^5.0@RC",
        "drupal/workflow": "^1.0",
        "drush/drush": "^9.0.0",
        "kint-php/kint": "^2.2",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "~8.5"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ]
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold",
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"]
        },
        "patches": {
            "drupal/domain": {
                "Drupal Domain New Content Type Domain Fields": "https://www.drupal.org/files/issues/2018-03-15/2953168-da-form-display-13.patch"
            }
        }
    }
}


texts: HELP! Can't make glossary using taxonomy term name

texts:
I'm using Drupal 8.0.2 and I'm trying to create a glossary of taxonomy terms by name. I have setup the view as follows:

Unformatted list
Fields: Taxonomy term: Name
Filter: Taxonomy term: Vocabulary (= Fruit Name)
Sort: Taxonomy term: Name (asc)

Stopping here the preview shows all Fruits by name (a-z) as expected.

Now when I add the following Contextual Filter:

Taxonomy term: Name
Type: Fixed
Fixed value: a
More: Glossary mode
Character limit: 1

The preview is empty, and the page returns a 500 error. I have done this successfully many times using Content: Title, but it never works using Taxonomy: Name. Can anyone tell me why this won't work using taxonomies?


texts: How to use the Profiles2 module for Drupal

texts:
I would like to use the Profiles2 module for Drupal 7 to create user profiles that are separate from user accounts.

I'm trying to find out what is the url for editing the user profiles created with the Profiles2 module? For example:

    http://www.example.com/url-for-profile-editing-page

And what is the template file I have to modify in order to cutomize this page?

Does anyone know?


texts: How to clear cache bins via the admin interface

texts:
Drush will allow you to selectively clear caches. CSS/JS or views for example.

Is there a way to do this via the admin interface, or a contrib module to do it? I don't have access to drush on a server and the cache rebuild is not reliable so it would be nice to just clear the cache bin that I need to.


texts:
I hope I'm not breaking any rules, but I wanted to cross-post this --- it is in the stackexchange for 'geographic information systems', but now I think the problem may be more on the Drupal side.

https://gis.stackexchange.com/questions/41223/openlayers-toggle-visibility-of-layer

I think the problem I'm having is in two things:

I'm not sure how best to get a handle on the map object in jQuery.
There seems to be a separate issue where strangely the click event is being fired twice.

EDIT: What I'm in effect trying to do is have the switchers below the map behave in the same way as the switchers in the right-hand-side grey switcher widget supplied by the openlayers library itself. See the screenshot.

I'm copying the question here, for the use of search engines etc.

I'm using OpenLayers in Drupal and am stuck while trying to make a layer toggle on and off (as it does from the right-side layer switcher).

See this map.
http://dev.lambeth.coop/map

Click on food growing projects.

EDIT: I've changed the code to show the Drupal-specific elements.

(function ($) {
  Drupal.behaviors.openlayers_switcher = {
    attach: function(context, settings) {
      $(document).ready(function() {
        $('[id^=openlayers-switcher-block--]').click(function(e) {
          $(this).toggleClass('active');
          // 27 is the length of 'openlayers-switcher-block--'
          // layername is the string following that.
          var layername = e.target.id.substring(27);
          var ol = $('.openlayers-map').data('openlayers');
          var layers = ol.openlayers.getLayersByName(layername);

          // this doesn't work
          // if (layers[0].visibility) {
            // layers[0].setVisibility(false);
          // }
          // else {
            // layers[0].setVisibility(true);
          // }
        });
      });
    }
  }
}(jQuery));

When I try to toggle visibility - the visibility doesn't change.

EDIT: So it appears that the entire click function is being called twice.

I've tried putting these lines (in various combinations) at the beginning of the function, as these have been suggested in google searches for 'click events firing twice' etc.

$('[id^=openlayers-switcher-block--]').click(function(e) {
  e.preventDefault();
  e.stopPropagation();

... but these don't help - I still get the function called twice.

In any case, I'm new to openlayers and would be grateful for a way forward!

Thanks!


texts: Help understanding Drupal form creation/content creation

texts:
I am fairly new to Drupal 7.9 and still trying to get a hang of it. Understandably it has a learning curve which I am trying to scale at the moment.

My challenge here is to basically create a page that has some backend processing to it. The front page consists of form elements (mostly textboxes) arranged in a tabular format.

A little bit of exploring and I reckoned I might need to create a kind of content type and then add content. But I got nowhere with this.

Then I discovered the webform module that lets me create form elements and provides a bunch of operations. But it doesn't necessarily allow me to display my form elements in tabular format.

So before exploring on my own again, I felt it would be right to ask questions from you guys.

Anybody with any leads on this ?

Thanks much !!!

Parijat


texts: "An AJAX HTTP error occurred.HTTP Result Code: 200"

texts:
I'm new to Drupal, and I'm working with a Drupal site that someone else wrote. From the admin menu, when I go to Structure -> Pages -> Edit Content -> Gear Menu -> Edit (or Settings), Drupal throws up this error:

  "An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path:
  /panels/ajax/editor/edit-pane/panel_context%3Apage-join_step_two%3Apage_join_step_two_panel_context/4
  [...] RESPONSE = nullnullnullnullnullnullnullnullfalseCancelled: Error
  bad character content for element
  'data_key'________nullnullnullfalsenullnull"

The code is also inserting the line

  "RESPONSE = nullnullnullnullnullnullnullnullfalseCancelled: Error bad
  character content for element 'data_key' ________
  nullnullnullfalsenullnull"

at the bottom of every page.

I know that Firebug can cause the Ajax HTTP 200 error, but I don't have it installed. I've spent hours looking through help pages for this error, and nothing has worked. Can you help? Thanks!


texts: Moving a DB table into a different module

texts:
Here is cleanetica_advanced.install file (of a "custom" module containing particulars of the site we work on):

<?php
function cleanetica_advanced_schema() {
  $schema['video'] = array (
    'description' => 'Videos with HTML titles',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key for our table of videos',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'urlinfo' => array(
        'description' => 'The string referring to the video',
        'type' => 'varchar',
        'length' => '255',
        'not null' => TRUE
      ),
      'title' => array(
        'description' => 'The title for a video, used in admin part only',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
      'richtitle' => array(
        'description' => 'The HTML-formatted title for a video',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}

function cleanetica_advanced_update_1(){
  drupal_install_schema('cleanetica_advanced');
}

I now think that it is better to create a separate module to manage 'video' database table and related things.

The trouble is that I have already created 'video' DB table. How to move/transfer a table into an other module?


texts: How can I remove content from the front page?

texts:
Made page--front.tpl.php. Created the view for content-type: news for example. Then put the view block in a block region. View block - only display news type limit at 1 or 2.

But when viewing the front page, all content types' content shows up on the front page along with the view block. I checked that it was managed by Display Suite but it shouldn't show show all contents on front page.

Why does this happen?

Update

Uncheck "promoted to front page" checkbox on all entries and it worked.

Other question:

"No front page content has been created yet.
Add new content"

How can I remove this text above on front page? I am using blocks most of the time, so text shouldn't be there.


texts:
Is there any module that can help me theming the "add content" page?

I'm also looking for a way to allow the use of the "add content" menu only to the users who paid.

When I talk about "add content" page, I'm actually talking about the template used when creating for example a new article page.

I don't want to give access to other users to the following fields, and basically change the whole look of that page.

Menu settings
Revision information
URL path settings
Comment settings
Authoring information
Publishing options


texts: Where in the page generation pipeline can an HTML beautifier be placed?

texts:
I need to view the HTML generated by Drupal and it is pretty hard. If I want to the final output to be put through an HTML beautifier before sending it off to the client where would I do that?

I am sure some of the page optimization utilities on the admin/config/development/performance or the advagg module are at the right place in the pipeline. What stage or APIs would I have to hook into to accomplish something this?

Are there any APIs which can be hooked into to accomplish this or even modules to this?


texts: Getting the number of Flood events within threshold?

texts:
The FloodInterface has 4 methods:

register - which adds an event
clear - which clears an event
isAllowed - which checks to see if the number of logged events is greater than the threshold
garbageCollection - removes expired events

I'm creating an EntityForm and need to use the number of flood events to conditionally set certain form elements, does anyone know if there is a way to do this?


texts:
I've a node, I'm trying to theme the same with the title of the node. I've written the code for it. Now when looking the source code, the twig file is showing also, but it is directly taking node twig.

The suggestion is

$suggestions[] = 'node__' . $title;

The suggestion when I debug is getting the value as

node--this--is--test.html.twig

I've tried single space also,

node--this-is-test.html.twig

It is also not working.


texts: Open an image in a new pop up window when form submit button is clicked in Drupal 7

texts:
I have a form with only a submit button in it and I want to display an image in a new pop up window whenever form submit button is clicked in Drupal 7 node.

function custommodule_my_form($form, &$form_state) {
$imgurl = $form_state['build_info']['args'][1];
$form['submit'] = array(
    '#value' => 'Print Coupon',
    '#type' => 'submit',
);
return $form;
}

The image is present in the loaded node and I already have its URL inside a variable $imgurl.

Now how can add an attribute in this form so that $imgurl opens up in a new window whenever this submit button is clicked.

$form['submit']['#attributes']['onclick'] = ??


texts: Drupal 7: Cron claims webform module function to be undefined

texts:
I cant really figure this out.

I have a module which interacts with the webform module which just works perfectly fine.

But now I wanted to create a cron which updates certain submissions, but the cron function claims that suddenly the webform function webform_get_submission is undefined although all other mymodule functions use webform functions without any issues. How come?

// a whole lot functions which use webform functions
// [...]

function mymmodule_cron() {
    $conf = mymmodule_defaults();

    // check cron run
    if(true /* for testing */){

        // set writable User
        global $user;
        $original_user = $user;
        $old_state = drupal_save_session(FALSE);
        $user = user_load(1);

        // fancy sql statement
        $sql = array();
        // [...]
        $sql = join(" ",$sql);
        $result = db_query($sql);

        $queue = DrupalQueue::get('mymmodule_cron_archiveanon');

        foreach ($result as $row) {
            $row->anon = true;
            $queue->createItem($row);
        }

        // restore default user
        $user = $original_user;
        drupal_save_session($old_state);
    }

}

function mymmodule_cron_archiveanon_wrapper($item){
    $node = node_load($item->nid);

    if( function_exists('webform_get_submission')) {
        die("Yep.");
        // $submission = webform_get_submission($item->nid, $item->sid);
    }
    else {
        die("Nope.");
        // dies here
    }

    // custom function
    // mymmodule_contract_archive($node, $submission, $item->anon);

}


texts:
I am using Drupal 7 and drush 7.4.0. How do I handle array variables with drush?

For example, I have a variable, social_sharing, for which

drush vget social_sharing

Produces:

facebook: facebook
google_plus: google_plus
linkedin: linkedin
twitter: twitter
pininterest: pininterest

Using a drush command,

How can I get the value of only facebook using drush vget?
How can I delete one specific variable? for example if I want to remove google_plus from the list using drush vdel?


texts: Drupal Print PDF module with Chinese characters

texts:
I'm using the Print PDF module, but cannot get Chinese characters to display. I have tried DOMPDF (which displays as ?????), and TCPDF (which displays rectangles). I have tried changing all the settings (Use dompdf's Unicode Mode, dejavusans font etc...) but nothing works. What could I be missing?

I have set up mbstring in my php.ini as follows:

mbstring.detect_order . . . . . . . . . . . . .auto

mbstring.encoding_translation . . . . . . . .On

mbstring.http_input . . . . . . . . . . . . . . .auto

mbstring.http_output . . . . . . . . . . . . . .UTF-8

mbstring.http_output_conv_mimetypes . .text/|application/xhtml+xml

mbstring.internal_encoding . . . . . . . . . .UTF-8

mbstring.language . . . . . . . . . . . . . . . .Neutral

mbstring.strict_detection . . . . . . . . . . .Off

mbstring.substitute_character . . . . . . . .no value

EDIT: It seems that I need to add the Firefly Sung font for this to work, but I still can't figure out how with respect to Drupal. Also - it seems you can only set one font for the entire site - not one font per language, which is what I want?

Thanks


texts: Getting "The form has become outdated" error

texts:
I have a multistep node form.
Half way through the form through a popup dialog user is asked to login if they have not logged in prior.

Upon successful login when proceeding with next page of the node form, I get this validation error:

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

I understand it is because drupal_validation_form() verifies $form['#token'] and $form_state['values']['form_token'] are the same.

How do I avoid this, as this is a special use case (and it's not forgery by some external stuffs).

Any input on this front?