texts: How to set value in form validate for later validation functions

texts:
Problem

I'm adding the user register form onto the node create form with hook_form_alter.

The problem is the first step of account validation always fails because Drupal doesn't save Username to form_state['values']['name']. (I think because I'm combining two entity forms (user and node) and perhaps because it's not needed for the default entity node form?)

Either way I have 4 validation functions that run in $form['validate'];

0 (String, 18 characters ) node_form_validate | (Callback) node_form_validate();
1 (String, 39 characters ) commercecurrency_node_form_validate | (Callback) commercecurrency_job_advert_form_validate();
2 (String, 22 characters ) _editnode_validate | (Callback) editnode_validate();
3 (String, 26 characters ) user_account_form_validate | (Callback) user_account_form_validate();

I'm trying to set the value in _editnode_validate so $form_state['values']['name'] is set when user_account_form_validate runs.

However the following code although it changes the value in _editnode_validate, doesn't save the value for the other validation functions. How can I get it to store the new value?

function _editnode_validate ($form, $form_state)

   $test_value = $form_state['input']['name'];
   $form_state['values']['name'] = $test_value;

(Both _editnode_validate and user_account_form_validate are added in hook_form_alter, and the code for _editnode_validate is in the hook_form_alter module.)


texts: Collapsible items in menu administration

texts:
In sites with a lot of nested menu items on a menu (e.g the main-menu) administration becomes painful. Is there a module which will add expand/collapse capabilities to the admin/structure/menu/manage screens?

This has also been discussed in http://drupal.org/node/521546 but doesn't seem to be resolved.


texts: Views page title using field of webform submission

texts:
I created a page result table from webform submission by using Views. I define the path (result-here).

I want the title page pulled from one of the field. I already installed page_title but this is not possible.

Is there any trick or module to do this.


texts: Multiple form submissions sorted by user

texts:
Here's my case:

I have site with 5 forms. These can be filled in by user assigned with the a 'client' role. They can view and edit their own submissions and fill in forms multiple times, this works all as expected.

Now I'm looking for a way to display all submissions of all forms filtered by user. So when the site admin clicks on a client he can see a list with all submissions that this particular user has made.

I've been trying to tweak the default webform submissions view, create new views based on user, create a new view based on webform submissions with different relationships and contextual filters,.. unfortunately all without any luck.

I've been looking around but haven't found a good answer yet, I do apologize if I overlooked and this question has already been asked and properly answered.

Thanks a lot in advance.


texts: Is Entity Translation module compatible with Internationalization and can they be used to translate menus?

texts:
I installed the entity translation module for Drupal 7 and it works fine.

However, I also want to translate menus and I found that Internationalization module can do that.

The question is: are they compatible at all? If I install internationalization module will it not break the entity translation one?


texts: Adding group content to an organic group doesn't persist after submit action for hook_form_alter

texts:
In the submit handler I wrote for my implementation of hook_form_alter for a node edit form, I can successfully add a group content node to an OG using og_group() - og_is_member() returns TRUE after I call og_group(), whereas it doesn't before the call to og_group().  However, if I re-edit the node, og_is_member() no longer returns TRUE (the first time), and og_group_ref is not set as I had hoped.

Here's the code I use in my submit handler:

$ret = og_is_member('node', $gid, 'node', $node);
dsm($ret, 'is the node a member of the group?');     // nope!
$values = array(
  'entity_type' => 'node',
  'entity' => $node,
);
og_group('node', $gid, $values);
$ret = og_is_member('node', $gid, 'node', $node);
dsm($ret, 'is the node a member of the group now?'); // returns TRUE

Doing a Google search, I have found numerous instances of people saying that something very similar to the above works for them, and indeed, it does work for me - it's just that the change doesn't persist.

Anyone know why that might be the case?
TIA!
Lee

[8pm edit: add (mostly) full hook and submit handler functions, as requested.  I cut out some code handling other forms, etc.]

/**
 * Implements hook_form_alter().
 */
function my_module_utils_form_alter(&$form, &$form_state, $form_id) {

  if ( preg_match('/_node_form/', $form_id) && isset($form_state['field']['og_group_ref']) ) {
    // Editing a node which has OGs: process Audience and/or Program term reference fields
    if (isset($form_state['field']['field_audience_term_']) || isset($form_state['field']['field_program_term_'])) {

      // SNIP, SNIP - manipulate taxonomy term fields on node edit forms...

      $form['#submit'][] = 'my_module_node_edit_submit';
    }
  }

  // SNIP SNIP - handle other forms
}

/**
 * Process a node edit submission.
 */
function my_module_node_edit_submit($form, &$form_state) {
  // init arrays
  _my_module_set_up_arrays($userOGs, $aud_ary, $pgm_ary);
  $node = $form_state['node'];

  // for each program/audience which this user has visibility to:
  //   if program/audience is selected, select the corresponding OG for the node
  //   if program/audience is not selected, deselect the corresponding OG for the node
  foreach ($aud_ary as $key => $aud) {
    if (isset($userOGs) && in_array($aud, $userOGs)) {
      $gid = array_search($aud, $userOGs);

      if ($form['field_audience_term_'][LANGUAGE_NONE][$key]['#checked'] == true) {
        if (!og_is_member('node', $gid, 'node', $node)) {
          dsm('GID to ADD for Audience '. $aud . ': ' . $gid);
          og_group('node', $gid, array('entity' => $node));
        }
      } else if (og_is_member('node', $gid, 'node', $node)) {
        dsm('GID to DROP for Audience '. $aud . ': ' . $gid);
        og_ungroup('node', $gid, 'node', $node);
      }
    }
  }

  foreach ($pgm_ary as $key => $pgm) {
    if (isset($userOGs) && in_array($pgm, $userOGs)) {
      $gid = array_search($pgm, $userOGs);
      if ($form['field_program_term_'][LANGUAGE_NONE][$key]['#checked'] == true) {
        if (!og_is_member('node', $gid, 'node', $node)) {
          $ret = og_is_member('node', $gid, 'node', $node);
          dsm($ret, 'is the node a member of the group?');
          dsm('GID to ADD for Program '. $pgm . ': ' . $gid);
          $values = array(
            'entity_type' => 'node',
            'entity' => $node,
          );
          $ret = og_group('node', $gid, $values);
          $ret = og_is_member('node', $gid, 'node', $node);
          dsm($ret, 'is the node a member of the group now?');
        }
      } else if (og_is_member('node', $gid, 'node', $node)) {
        dsm('GID to DROP for Program '. $pgm . ': ' . $gid);
        og_ungroup('node', $gid, 'node', $node);
      }
    }
  }
  return $form;
}


texts:
I'm trying to get a menu with my custom classes.

I would like to be able to

// class of the whole ul

// add class "with-sub" if has children
submenu

 // add class sub-menu to sub menu ul

// add the title of the parent as first item of the list
TITLE OF THE PARENT

// add a class to all sub-menu items
 Submenu item

For the first level it's fine. I can use menu_tree and menu_link to get what I want.

I would like to know how to use $sub_menu = drupal_render($element['#below']) and customize the sub menu list.

I don't want to use any module, I want to do all through the template.php.

Thanks in advance


texts: How 'checkboxes' form element supposedly can have #default_value if there is nothing to make this work? Or is there?

texts:
So, documentation indicates that 'checkboxes' element is making use of '#default_values' property. There are multiple threads indicating that it's possible, like:

Checkboxes: how do I set the default values or show the user defined values using Form API?
How to check a checkbox by default in forms api

And many more.

However, it doesn't work for me, although I'm currently trying it in Views custom field handler, but I think it shouldn't matter. I'm looking at the code of Drupal core to see how it handles #default_value for 'checkboxes' element:

https://github.com/drupal/drupal/blob/7.x/includes/form.inc#L3290-L3351

So, nothing from the 'checkboxes' #default_value is being put into created 'checkbox' elements. But there is more - 'checkbox' type doesn't even use #default_value property to decide if it is checked or not, but rather #value property, and that one is empty if form has not been submitted.

Let's read description of #default_value from documentation again:

  The value of the form element that will be displayed or selected initially if the form has not been submitted yet.

And let's look at the code not having any expected reference to #default_value again:

function form_process_checkbox($element, $form_state) {
  $value = $element['#value'];
  $return_value = $element['#return_value'];
  // On form submission, the #value of an available and enabled checked
  // checkbox is #return_value, and the #value of an available and enabled
  // unchecked checkbox is integer 0. On not submitted forms, and for
  // checkboxes with #access=FALSE or #disabled=TRUE, the #value is
  // #default_value (integer 0 if #default_value is NULL). Most of the time,
  // a string comparison of #value and #return_value is sufficient for
  // determining the "checked" state, but a value of TRUE always means checked
  // (even if #return_value is 'foo'), and a value of FALSE or integer 0 always
  // means unchecked (even if #return_value is '' or '0').
  if ($value === TRUE || $value === FALSE || $value === 0) {
    $element['#checked'] = (bool) $value;
  }
  else {
    // Compare as strings, so that 15 is not considered equal to '15foo', but 1
    // is considered equal to '1'. This cast does not imply that either #value
    // or #return_value is expected to be a string.
    $element['#checked'] = ((string) $value === (string) $return_value);
  }
  return $element;
}
/**
 * Processes a checkboxes form element.
 */
function form_process_checkboxes($element) {
  $value = is_array($element['#value']) ? $element['#value'] : array();
  $element['#tree'] = TRUE;
  if (count($element['#options']) > 0) {
    if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
      $element['#default_value'] = array();
    }
    $weight = 0;
    foreach ($element['#options'] as $key => $choice) {
      // Integer 0 is not a valid #return_value, so use '0' instead.
      // @see form_type_checkbox_value().
      // @todo For Drupal 8, cast all integer keys to strings for consistency
      //   with form_process_radios().
      if ($key === 0) {
        $key = '0';
      }
      // Maintain order of options as defined in #options, in case the element
      // defines custom option sub-elements, but does not define all option
      // sub-elements.
      $weight += 0.001;
      $element += array($key => array());
      $element[$key] += array(
        '#type' => 'checkbox',
        '#title' => $choice,
        '#return_value' => $key,
        '#default_value' => isset($value[$key]) ? $key : NULL,
        '#attributes' => $element['#attributes'],
        '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
        '#weight' => $weight,
      );
    }
  }
  return $element;

So, it doesn't work, and looking at the code it shouldn't work. What am I missing?


texts: Clone a SelectQuery instance : what am I doing wrong?

texts:
I've got a SelectQuery which I've created using db_select(). Then, after I've executed the query, I'm trying to clone it as I need to generate a few more queries based on the original one.

However, for some reason the clones I get from the original query doesn't seem to be clones. This is what I do.

// Create query
$q0 = db_select('track', 't');
$q0->fields('t', array('id','number','title');
[...]
$tracks = $q0->execute()->fetchAll();

// Clear fields on original query.
$fields = &$q0->getFields();
$fields = array();

// Clone original query. The below queries should not have
// any fields set as they just got cleared above.
$q1 = clone $q0;
$q2 = clone $q0;

// This gets weird. The queries $q1 and $q2 should be separate
// clones, independent of each other. So should their fields.
// However, setting fields on $q1 also sets fields on $q2.
$q1->fields('t', array('id'));

// Output : Array ( [id] => Array ( [field] => id [table] => t [alias] => id ) )
print_r($q2);

The fields() function on SelectQuery simply sets an array (see below). I thought that cloning an instance of a class containing an array would copy those arrays by value...and not by reference? Is this a special cloning "feature"?

protected $fields = array();

public function &getFields() {
  return $this->fields;
}


texts:
I want to make entity in Drupal 8 called cash that store only numeric value (integer or float). I think, that entity not need translation.
Is it possible for us to create custom entity without language/translation?


texts: Limited popup like once per month and user

texts:
Is there a module for Drupal that has the following options:

show a popup once in a month/day/...  should be configurable
save this information in a cookie or else
the popup should display some text and nothing else


texts: How to install with composer external library that drupal module depends on

texts:
Module bootstrap_languages depends on external library of same name how do we ask composer to require the external library that needs to go to libraries/bootstrap_languages folder

The project's composer.json already includes installer-paths but how can I make use of them ?

    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        ....
        "libraries/{$name}": [
            "type:drupal-library"
        ]

NOTE: the module itself has not taken care of this dependency


texts: How do I change order of completion rules in checkout?

texts:
How do I change the order in which completion rules fire?
There is a default Completition reaction rule. I wanted to add a second rule which executes some custom PHP but it's never executed.
I see no way to change the weight as in other rules. I also tried adding what I need as an action in that default rule, but it also doesn't seem to fire.
This is the reaction rule that fires on order completion.
{ "rules_completion" : {
    "LABEL" : "completion",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "php_eval" : { "code" : "jch_send_quote()" } },
      { "commerce_checkout_complete" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }

This is the code for jch_send_quote() which doesn't seem to fire.
function jch_send_quote(){
    global $user;
    watchdog('dev', 'jch_send_quote running here');
    drupal_set_message($user->uid);
        die('jch_send_quote running here')
}

What am I missing?


texts:
I would like to set some functionality in a module only on if caching is turned off.

Is there a way to check in code if caching is on or off?


texts: Is the "www" in the database for the site confguration?

texts:
I have recently helped launch a site and there are some cross domain issues between "www.website.com" and "website.com"

I was chatting with Cloudways tech support and he mentioned that if I remove the "www" from the database for my site settings I wouldn't be having the issue.

What I ended up doing was modifying the .htaccess to redirect to "www.website.com" for now, but I still have the question: Is the "www" for the domain name in site information stored in the database? If so, would you really want to edit that?


texts:
I want to change a label/string on a node edit form for a date field.

The label is, "Show end date" - I want to change this to, "Show end date (optional)", but I can't find where this is set anywhere. My guess is that it is some sort of theming change - I took a look at the node_form and saw nothing.


texts: How can I add this additional context object to a Page Manager variant?

texts:
Here's my scenario. I'm using Page Manager and Entity Construction Kit.
The ECK entity is called "Session" of bundle "Session".
The User has a field that is referencing another ECK entity called "Teacher" of bundle "Teacher".
On the ECK entity "Teacher" I have a integer property that I need to check before I can grant that teacher access to the session/session/add page.
At this point, I have the "Session" and the "User" as a context and all of their fields and properties i.e. %session and %user. But I can't load the value of the referenced field as a context because it's not available. I'm imaging that this context should be something like %user:field-referenced-teacher:my-property but alas, that's not available.
Any ideas how to get?


texts: Override taxonomy term display page with panel page

texts:
I am having a menu built using taxonomy terms which links to a URL pattern like shop/[Term name] this is a dropdown menu.
I have created a panel page which takes an argument in the URL i.e (shop/!argument).
In the panel I have added a contextual filtered(has Taxonomy term) view and checked "send arguments" option in settings.
so obviously the taxonomy term display page is where I land when clicking the links.
I don't want to use the taxonomy term panel or the views page for taxonomy which comes with drupal core itself.
I want my panel page to override the taxonomy term display page
this is only for two types of vocabulary terms, any ideas how?


texts: Make autocomplete window appear above accordion pane

texts:
I have created a node add form using the field group module to put the form in a jQuery accordion.

I have a auto-complete field that is at the bottom of one pane so the div that appears that lets users choose from the auto-complete options is behind the pane below it as it has overflow: hidden. Here is an image of the problem:

I've fixed this behavior by changing 2 lines in autocomplete.js in the populatePopup function:

//var position = $input.position();
// changes to:
var position = $input.offset();

// and

//$input.before(this.popup);
// changes to:
$('body').append(this.popup);

As the auto-complete div is now appended to the body it appears above everything else.

This is great but the problem is I don't want to start hacking Drupal core js files.

I could copy the whole autocomplete.js to a new file and then replace the whole thing, but really I just want to override the populatePopup function.

Is it possible to do this?

(I've tried copying the populatePopup function into my own js file but I get the error Drupal.jsAC is undefined.)


texts:
I am building a configuration form in an admin menu.  I'll have some input fields inline at top, and below, a table of data.  I'd like to render a view of the data in the table so it can handle the paging, etc.

How can I access the view and render it?


texts: How to send values to an external database with a custom module?

texts:
Working on Drupal 7.54

I am more a site builder than a developer but now I have no choice, I need to write a little module for Drupal 7.

So, I was wondering if someone could help me to write this custom module (at least help me to start).

Here is my problem :

I need to send form values to an external database.

For the moment, I managed to tell Drupal that it will need another database (in settings.php, everything is fine here).

Following "Inserting data to external DataBase
", I managed to create a little form to add a new line in the external database (using hook_form, hook_form_submit, db_set_active and db_insert).

Now I would like to complete this custom module to achieve this :

an user open the node edit form
an user submits changes
the form is submitted
the form values are saved as usual on Drupal database
AND the same values are saved on the external database

Finally, I need a module to synchronize Drupal nodes with external database tables.

I suppose this is something totally doable and easy for someone used to Drupal API.
Thanks in advance for any help on this.

PS : you may find a first brainstorming on this problem here : How to edit external database from Drupal 7 interface?

Related questions

How to define and use an external database connection in a custom module


texts: Can I merge translation between 2 sites?

texts:
I have site 1 and site 2. I've been doing some manually translations at: admin/config/regional/translate/translate and also I updated the translation at: admin/config/regional/translate/update in both sites.

I'd like to merge the translation betweeen these two sites. Can I do this?


texts:
is there a way to ajaxify simplenews subscribe to newsletter block?
I was thinking of hook_form_alter ing it and adding my ajax callback, But its not working.

my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'simplenews_block_form_7182') {
    $ajax = array(
          'callback' => 'simplenews_block_form_validate',
          'wrapper' => 'simplenews_wrapper_block',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array('message' => '')
        );
    $form['submit']['#executes_submit_callback'] = TRUE;
    $form['submit']['#ajax'] = $ajax;

but now when I trigger the submit button i get
Fatal error:  Call to undefined function simplenews_block_form_validate() in /includes/form.inc on line 1460


texts: In my checkboxes if i have a 0 value it select this checkbox

texts:
I have in my form a type 'checkboxes' form.

    // Form for the severity checkboxes.
    $kkkk_severity_levels = variable_get('kkkk_severity_levels', array());

    // Declare empty options array.
    $kkkk_severity_options = array();

    // Loop through each severity level and push to options array for form.
    foreach (watchdog_severity_levels() as $number_select => $severity) {
      $kkkk_severity_options[$number_select] = drupal_ucfirst(
        $severity);
    }

    // Checkboxes form.
    $form['kkkk_severity_levels'] = array(
      '#type'          => 'checkboxes',
      '#title'         => t('Type of log messages'),
      '#options'       => $kkkk_severity_options,
      '#default_value' => array_values($kkkk_severity_levels),
      '#required'      => TRUE,
    );

In these lines of code the watchdog_emergency has a key 0 so when i select something from checkboxes i take selected also emergency always as it gets me out : e.g if i select 'info' with key 6 it gets me out:

6 (String, 1 characters ) 6
0 (Integer) 0
1 (Integer) 0
2 (Integer) 0
3 (Integer) 0
4 (Integer) 0
5 (Integer) 0

7 (Integer) 0
and so it selects also the 'emergency' with key as 0... How I can solve this problem?


texts: Is there a better way of getting specific pieces of data from taxonomy_term_load()?

texts:
I have a taxonomy that has several fields attached to it. If I do a taxonomy_term_load($tid) on a specific item, it returns a huge object with multiple levels of nested arrays. I know which "parent" item (i.e. field name) I want, so I can do something like this:

$track_tax = taxonomy_term_load($value);
var_dump($track_tax->field_track_icon);

But even this returns a lot of nested levels:

array(1) {
  ["und"]=>
  array(1) {
    [0]=>
    array(15) {
      ["fid"]=>
      string(3) "702"
      ["alt"]=>
      string(0) ""
      ["title"]=>
      string(0) ""
      ["width"]=>
      string(2) "36"
      ["height"]=>
      string(2) "36"
      ["uid"]=>
      string(1) "1"
      ["filename"]=>
      string(24) "strategies_at_retail.jpg"
      ["uri"]=>
      string(44) "public://track_icon/strategies_at_retail.jpg"
      ["filemime"]=>
      string(10) "image/jpeg"
      ["filesize"]=>
      string(4) "1129"
      ["status"]=>
      string(1) "1"
      ["timestamp"]=>
      string(10) "1338391429"
      ["type"]=>
      string(5) "image"
      ["rdf_mapping"]=>
      array(0) {
      }
      ["image_dimensions"]=>
      array(2) {
        ["width"]=>
        string(2) "36"
        ["height"]=>
        string(2) "36"
      }
    }
  }
}

I know I can get the uri by doing something like this:

$uri = $track_tax->field_track_icon["und"][0]["uri");

Is there a better way? Some other function that will return specific pieces? Or do I need to address it level by level?


texts: How do I create and theme an image link in Drupal 7 Views?

texts:
Ok... here goes. I've had a lot of trouble trying to track down any sort of example like this, and the Drupal 7 Views documentation doesn't even document the views-view-field.tpl.php.

I'm trying to override the default display for a field inside of a view because the default field html content is not at all sufficient to my needs. I can almost do it, except that the views module likes to inexplicably wrap the field content in a  that I cannot override through the templates. Also I'm forced to hack into the field's $row variable internals directly, which does not strike me as a good long term strategy.

views-view-fields--slider.tpl.php

  <a href="<?php echo $fields['field_slide_link']->content; ?>">
    <img src="<?php echo $fields['field_slide_image']->content; ?>">

views-view-field--field-slide-image.tpl.php

<?php echo image_style_url('slide', $row->field_field_slide_image[0]['raw']['uri']); ?>

views-view-field--field-slide-link.tpl.php

<?php echo $row->_field_data['nid']['entity']->field_slide_link['und'][0]['safe_value']; ?>

So to summarize the two problems:

Diddling with the $row internals directly makes me quite uncomfortable. Surely there's a better and safer way of getting the not quite raw field values that I care about.
The rendered field content is always wrapped in a div.field-contain and I cannot eliminate it through the template, as I would have expected. I'm loath to call strip() to remove the html (I can think of several use cases where I might not want that wrapper).


texts:
I searched for a module provide notification like one exist in facebook website.
I found user notification but it's for D6.
is There a module can i use for what i need?  thanks.


texts: How to show an image instead of a tab title for a field group?

texts: How can I show an image instead of the tab title of a field group?


texts: I want each user to create their own site-logo. This is not multi-site, this is a single site only. How can I do it?


texts:
I want to diplay all Flag Lists created by any user in the VBO. I am able to get the Flags, however, not the Flag Lists. Could someone guide me how to achieve this?

Thanks


texts:
I've been working on a Drupal site under a LAMP configuration. My client uses SQL Server, so after I'm done with development I need to move the site over to their configuration. I work on Linux, so I have no way to test the site live (I can remotely connect to my client's server but if I want anything changed I have to go through their IT department, which is painful and slow at best).

I found this module, driver for SQL Server, but from the instructions I gather this is for a fresh Drupal install. Could it work, if I already have some work done, to move my current DB over to their server? If not, is there another option to keep working on MySQL and later migrate to SQL 2008?

I'm not familiar with SQL Server, so any help is appreciated.


texts:
I have the form which is created through Webform module and now I need to add one more text field but its value has to be unique and can be only the value from some predefined list of allowed values.

It's not the problem that value of the field be unique (I can enable it in text field settings) but I don't have idea how to limit the value of the field on one from predefined list of values.

Those strings are voucher codes that are sent to the clients by email, also there are a 1500 different codes.

If the user enters the code that was already used or enters the code that doesn't exist in the list he should get the notification that the code is not valid right away (Ajax) or on the form submit.

Can anyone can help me with this or direct me? I'll appreciate any suggestion...


texts: How to convert an order price to a different currency in Commerce 2?

texts:
The Stripe payment gateway only accepts JCB and Diners Club transactions in US dollars (no international currencies).

Most of the transactions on my site are in Japanese yen.

In fact, I would prefer to have everything in yen, but I want to try to handle JCB (major credit card in Japan) by somehow converting the JPY prices to USD and then billing in USD (of course, I will notify the user I am doing this).

Ideally, the flow looks like this:

User browses my store where prices are shown in JPY.
User adds a product to the cart.
User goes to checkout and chooses a payment method (if user chooses "Pay with Mastercard/Visa" (standard Stripe payment gateway), transaction proceeds as normal.
If the user chooses "JCB", price is converted to USD and then billed in USD.

How might I begin to implement this kind of conversion?  Or, is there a better approach/flow for converting the order price from one currency to another?


texts:
I am working on printing dates in more than a language. With Drupal 7, I used the following code.
<span class="arabic-date">
 <?php
   $arrayurdudays = array('', '', '', '', '', '', '', '');
   print format_date(time(), 'custom', ' l , d F , Y', null, 'ur');
 ?>
</span>

With Drupal 8 and Twig, I tried more than one way and it didn't work for me.
I downloaded the Configuration Translation module, but it didn't work in my case; I read there is a way to print it inside a file (.theme), but I didn't understand the method well. I need it inside the header file.


texts: How to add inline Javascript code properly with drupal_add_js for a Drupal Commerce checkout pane?

texts:
I have a custom checkout pane with a basic validation callback. That pane function commerce_checkout_xyz_pane_checkout_form adds some inline Javascript code with drupal_add_js().

The problem, that Javascript only appears on the initial form and is not added when the form is shown again after failed validation.

I thought about moving the drupal_add_js() to a $form['#after_build'] callback but I don't know if that's the right thing to do and how to do it.


texts: Featurize user roles and permissions can't update

texts:
I have added user roles and permissions to feature which I use to featurize general site configurations and theme settings.

In the past I believe this worked just fine, however, with my latest push the remote created additional roles instead of changing the names as I had done on dev. I deleted the old roles and kept the ones with the proper names. MySQL drupal.role shows that the roles now have new IDs also which I believe could be the cause of the problem. I shouldn't have deleted the roles that matched dev but since I already did, where do I go from here? Should I manually change the ID's in MySQL?

I'm working on a new site that isn't launched yet but will be importing users from another site.

Here you can see the original role IDs and what is on dev:

Here you can see the role ID's on prod now:


texts: Post update hook fails to run via Drush, but works via update.php

texts:
I've implemented hook_post_update_NAME to bulk import some files into Drupal (creating file and media entities for them). This hook runs correctly when I use update.php. But it seems to silently fail via drush updb.
My update hooks looks like this
/**
 * Creates SVG icons as media entities.
 */
function my_module_default_content_post_update_create_icons() {

  $module_handler = \Drupal::service('module_handler');
  $module_path = $module_handler->getModule('my_module_default_content')->getPath();

  \Drupal::logger('my_module_default_content')->notice('Importing icons from @path', ['@path' => $module_path]);

  $dir = new DirectoryIterator("$module_path/icons");

  \Drupal::logger('my_module_default_content')->notice('Directory contains @count items', ['@count', count($dir)]);

  foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {

      \Drupal::logger('my_module_default_content')->notice('Importing file @file', ['@file' => $fileinfo->getFilename()]);

      my_module_default_content_create_icon($fileinfo->getPathname());
    }
  }
}

This works fine via update.php. All the files are copied, relevant entities created, and messages logged to watchdog. When running drush updb I only get

[ok] Update completed: my_module_default_content_post_update_create_icons
[success] Finished performing updates.

None of my log messages are output (while using --debug option) to the screen or to watchdog.
My initial thought was a permissions issue, but if it's not outputting any of my log messages. I'm not positive the function is even being run. Adding in a die() on the first line of the function gave the exact same output/outcome.
Any ideas on what could cause this to silently fail when running via Drush?


texts: How to personalise menu links attributes

texts:
I met some problem with my menu items on my site. All content of the page is given in the "title" attribute of the item, like this: http://joxi.ru/Q2K53V5H9WXyxr I think it's not pretty cool for SEO and users. How to clear such a large title attribute of link?
Used module: Taxonomy Menu
Core: Drupal 8

I think problem could be solved with themisation of the menu.html.twig, but I don't know how to.

Hope for your advice!


texts: In Drupal 7 Views what is the php code to validate a field against a contextual filter argument?

texts:
Currently I am using the path url to pass in arguments:

path: /%/%/%

On the 3rd argument I am loading a Taxonomy term. I also have a field loaded called: field: device type

What do I have to put in my contextual filter validation PHP code? I did a dsm($view), but my device type shows recursion. I'm not sure how to reference the field properly to create a conditional to compare it to the contextual argument.


texts: Empty node workflow state on node after programmatically saving

texts:
I have saved a node programmatically, in the following way:

  $node_storage = \Drupal::entityManager()->getStorage('node');
  foreach ($entity_ids as $id) {
    $node = $node_storage->load($id);
    if (!$node) {
      continue;
    }
    $node->set('field_tags', $new_tid);
    $node->save();

After saving the node I am trying to edit it and I am getting the follow error upon submit.

InvalidArgumentException: The state '' does not exist in workflow 'draft' in Drupal\workflows\Entity\Workflow->getState()

I believe that this means that my node has no state.

How could I set the node's state?


texts: How To add user name and profile picture to Superfish menu

texts:
I am using Superfish module to obtain drop down menus. I would like to have one parent menu link as a username and user image, then child menu links will be under it when hovered over.

Example of this is airbnb.com when logged in.

I do not know much PHP and do most of my work with CSS and already created modules.


texts:
On a site we are working on I was asked why the page titles are wrapped with a span tag. We are not using a base theme.
I checked everywhere I could think of, but came up short.
In page-title.html.twig:
{#
/**
 * @file
 * Theme override for page titles.
 *
 * Available variables:
 * - title_attributes: HTML attributes for the page title element.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title: The page title, for use in the actual content.
 * - title_suffix: Additional output populated by modules, intended to be
 *   displayed after the main title tag that appears in the template.
 */
#}
{{ title_prefix }}
{% if title %}
  <h1{{ title_attributes }}>{{ title }}</h1>
{% endif %}
{{ title_suffix }}

At this point, title is a render array. It is passed in as a Markup object. Where is this happening?
The span doesn't hurt anything, but at this point I just want to find where that is occurring. Is there an option to switch that off? I can preprocess_page_title and strip tag it, but unless there is a good reason, I would rather not have it at all.


texts: how to add a class div on drupal 7 webform element?

texts:
webform generated each form component in this structure

  <input></input>

I like to add a div class on each input element

<input></input>

I looked into the form alter to alter form element with #field_prefix and #field_suffix

$form['submitted']['chinese_name']['#field_prefix'] = '
';
$form['submitted']['chinese_name']['#field_suffix'] = '
';

but it didn't work.


texts: How to show a trimmed version of the report?

texts:
When a user has access to a report, that report becomes user specific. But, how to show a trimmed version of the same report to other users?

I have used content access and ACL module to give per user access.


texts: Change mark-up with a textfield using Ajax

texts:
In a form I have a field where the user have to enter the name, after this I have to update a markup with data from an external DB using the textfield as a parameter, How can I do this or even Is this posible?

PD: I am using autocomplete to show a list of users when the user is writing in the field.
Thanks.

<?php
/*this part is in hook_form_alter*/
$form['submitted']['empleado']['#ajax'] = array(
'callback' => 'ajax_saldo_markup_callback',
'wrapper' => 'saldo-markup-reload',
);
$form['submitted']['saldo']['#prefix'] = '
';
$form['submitted']['saldo']['#suffix'] = '
';
$form['submitted']['saldo']['#markup'] = _busqueda_saldo_vacas($form, $form_state);
/*this part is in hook_form_alter*/

function ajax_saldo_markup_callback($form, $form_state) {
    return $form['submitted']['saldo'];
}

function _busqueda_saldo_vacas(&$form, $form_state){
$username = $form_state['values']['submitted']['empleado'];
/*DB Query's*/

    foreach ($result as $row) { //At the end I get only one data
    $form['submitted']['saldo']['#markup'] = $row->Data;
    }
}
?>

With this code It seems to work, with Devel, the property "#markup" changes, but is not displayed, if I change it to "#title", it is displayed.


texts: Error when trying to migrate comments to a clean D8 site: What's wrong with my .yml file?

texts:
I'm trying to migrate content from my current D7 site to a Drupal 8 installation.

I've managed to import some of the nodes, and now I want to import the comments for those nodes.

Every time I click on "run" (.../admin/structure/migrate/manage/importarComentarios/migrations/importar-comentarios/process/run) I get an error:

What am I doing wrong?

This is my migrate_plus.migration.importarComentarios.yml file:

id: importar-comentarios
label: Comments

migration_tags:
  - CSV

migration_group: importarComentarios

source:
  plugin: csv
  path: 'public://csv/exportar-comentarios-genericos.csv'
  header_row_count: 1
  delimiter: ','
  enclosure: '"'
  keys:
    - id
  column_names:
    0:
      nid: 'nid'
    1:
      created: 'created'
    2:
      body: 'body'
    3:
      autor: 'autor'
    4:
      cid: 'cid'
    5:
      titulo: 'titulo'
    6:
      mail: 'mail'

destination:
  plugin: entity:comment

process:
  entity_id: nid
  subject: title
  'comment_body/value': body
  'comment_body/format':
    plugin: default_value
    default_value: "html"
  # Migrate our custom field
  field_mail: mail
  field_nombre: autor
  status:
    plugin: default_value
    default_value: '1'
  created: created
  nombre: autor
  email: mail
  # The comment type (aka the comment's bundle).
  comment_type:
    plugin: default_value
    default_value: 'comentario'
  # The type of entity we're attaching this comment to.
  entity_type:
    plugin: default_value
    default_value: 'node'
  # The field we should attach this comment to. This is a field on your node.
  field_name:
    plugin: default_value
    default_value: 'comentarios'

migration_dependencies: {}

And this is the migration overview:

This is the overview

This is the destination

This is the process

And when clicking the source, I get:

  The website encountered an unexpected error. Please try again later.

My configuration is:

My content type is called contenido

And these are the fields of my comments

And my contenido content type has a comentarios field for comments


texts:
When I tried to do a feed import, I got the following error.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /batch?id=1726&op=do
StatusText: OK
ResponseText [Omitted text]

(There are quite a few similar errors on the web, for example https://www.drupal.org/node/1125060.)
When I changed the author field to 'site-admin' (see attached image), auto-complete seems running and popup the following error.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: http://site-prod.local/user/autocomplete
StatusText: OK
ResponseText: my_site_name | my_username
[url1]
[url2]
[url3]
[Search form]
[Primary tab: View (active tab)]
[Edit]
[Shortcuts]
[Broken links]
[Devel output]
[My username]
[Email]
[Omitted text]

The log message is the following.

Warning: Cannot modify header information - headers already sent by (output started at /var/aegir/platforms/production/drupal-7.27/includes/common.inc:2700) in drupal_goto() (line 703 of /var/aegir/platforms/production/drupal-7.27/includes/common.inc).

If I put exit() right after drupal_json_output(). The related problem seems resolving itself.
When I run drush -d -v search-index, the indexing stuck at around 61%. This indicates some problems with a node.


texts:
I am new to Drupal and am having trouble getting my custom HTML to take up most of the page. As you can see below, it is confined to the center and takes up a tiny percentage of the screen.

Here is the image of my module:

Thanks for all the help!


texts: Changing group visibility needs group content to be resaved when group content visibility field is set to "Use group defaults"

texts:
Drupal Commons 7.x-3.2
Organic Groups 7.x-2.1

Content type: Mygroup
Field: Group visibility - value: Public

Content type: Mypost
Field: Group - default value: Mygroup
Field: Group content visibility - default value: Use group defaults

Now when I create a group and a post based off on these content types everything is fine. As in everything is visible for all users.

Now when I change the Group visibility to Private I would except the post to not be visible anymore (because of the Use group defaults setting.

Unfortuanetely that's not working until I resave the post content. Then it will respect it's parent's settings.

This bug is mentioned in this video (around 6 min)

Does anyone know how to solve this problem?


texts: Drupal 7: adding an image and a link to a user page

texts:
I have a new Drupal 7 website with user profile pages like this one.

I'm new to Drupal and do not want to install any modules besides the core ones and the few written by me - because this will keep the site easy to maintain and upgrade for me at the beginning.

I have already written the 3 blocks displayed at my site's Triptych.

Now I'd like to add an image (will be a static Google map with a marker at user's city, for example: http://maps.google.com/maps/api/staticmap?sensor=false&markers=color:0x336699|Bern&&size=300x300 ) and a dynamic link to the user profile pages (i.e. the link depends on the user's id).

I.e. I know how to get user's city for my map:

$result = db_query('select field_city_value from {field_data_field_city} where entity_id=:uid', array(':uid' => array($viewer_id)));
$city   = $result->fetchField();

but I don't know how to extend the user profile page.

Please give me few hints on how to do it, which hook to use here and maybe few lines code.

And maybe anyone also knows how to add a Tab to a user profile page as well?


texts: How to unpublish content that is under moderation

texts:
I am using the Content Moderation module in Drupal 8.2 and I have noticed there is no way to re-unpublish a node once it has been moderated into a published state. I'm able to create a new draft of the content and moderate that through to published state but I can't find a way to actually unpublish the node.

There is a bug issue on DO that seems related, but looking at the patch it only adds a message informing you that you can't unpublish content directly once under moderation. Which makes sense as having content moderation enabled means you are handing over control of publish/unpublish to that module. But that leaves the question of how to actually unpublish a node that is under moderation?

I understand this module is currently experimental but am fairly sure I am missing something here.


texts: Add class-element to a link though a module (or can I implement theme_link in a module instead of in a theme)?

texts:
I'm the developer and maintainer of a module on the Drupal website. It implements an API so that a certain third party service can be easily integrated in Drupal.

I'm currently having the following problem: I need to add a class-element to the logout link. So my module has to arrange that all the these links Log out becomes the following: Log out

For the logout link in a menu it's easy, I have to implement hook_menu_link_alter().

However, I also want to catch all occurences where somebody is using l("Log out", "/user/logout"). The latter function calls theme_link, so if I would implement that, I think it could solve my problem.

So my questions are:

Can I implement theme_link in a module? If so, can somebody tell me how to do this?
Is there another way in which the above could be accomplished by means of a module?


texts: How to hook into Drupal 6 search process?

texts:
I need to modify the search results drupal generates to include selected content from some other D6 sister sites.  hook_search seemed like the obvious choice, but when I implement it, it's never invoked with the keywords I'm searching for:

function nmc_xsearch_search( $op = 'search', $keys = NULL ) {

    switch ($op) {

        case 'name':
            return t('Content');
            return $form;

        case 'search':
            dsm( "Operation: $op | Keys: $keys" );
                return $results;
    }
}

When I walk through this code in the debugger, my function nmc_xsearch_search() is hit twice.  The first time $op = 'name' and $keys = null.  The second time $op = 'name' and $keys = '1'.

When I put a breakpoint on node_search it is invoked four times - all before my nmc_xsearch_search() is hit.  The last time node_search is hit the provided parameters are: $op = 'search' and $keys = 'my search keywords'.

Basically I want my function to get the same invocation that node_search is getting so that I can access the keywords and modify the results array returned by hook_search.  Any ideas?


texts: Use a custom module to add JS to every page in Drupal 8

texts:
How can I use a custom module to add JS to every page with Drupal 8?

I've found lots of example scattered over the internet that maybe used to work but no longer work.


texts:
My website is using Drupal 7, secure login, and r4032login. I get this message when I log into a page that was redirected to the login page when access was denied:

  You are accessing  using an unencrypted connection. For your security,  only supports account logins using a secure protocol such as HTTPS. You can switch to HTTPS by trying to view this page again after changing the URL in your browser's location bar to begin with "https" instead of "http". Please contact  for help if this error continues.

This is untrue, as every time this message appears the sites url is https://www.mysite.com
What can I do about his message? What is the underlying cause? How can I suppress this if it can't be solved?

Update: This is not being caused by r4032login or secure login. I disabled and unistalled these module, and after logging in, the message is still displayed.


texts: How can I let authenticated users rebuild caches?

texts: Is there a way for authenticated users to clear the cache without giving them the administer site permission?


texts:
I have created a content type 'Property', has fields 'Property name','Address line1','Address line2','Address line3'.

I don't want to add duplicate properties in database, so that I want an AJAX call while filling above fields and check is there any property available in database or not with current provided values of fields.

If there is any one result, I want to show it on modal.

The only problem is, Where should I write an AJAX code?, And where will the business logic ?.

Is there any way to do this?. kindly suggest me. thank you.


texts:
I’m new to drupal, so I apologize if my questions are too basic

Any help would be appreciated

I’m using drupal 7 with Ubercart version 7.x-3.8

With Ubercart Auction module version 7.x-1.x-dev

I’m trying to create a car auctioning website, where users can place a car up for auction and other users can bid on it.

How do I enable authenticated users to be able to add ubercart products?


texts: Error, unmet dependencies at installation

texts:
i have an error at drupal installation with my custom profil - version 2. i have successfully created a custom profile - version 1 - and installation is ok, thus i know how to do it and it works.
Note: i am installing the Drupal files with composer.

i've tried hard without success to find a answer for my problem on the internet, essentially in those tread :

https://www.drupal.org/project/drupal/issues/2922417

https://www.drupal.org/project/drupal/issues/3045349#comment-13054710

I have this error on the last installation step "Configure site"

The website encountered an unexpected error. Please try again later.
Drupal\Core\Config\UnmetDependenciesException: Configuration objects provided by bsd_showcase have unmet dependencies: block.block.about (bootstrap_for_drupal_distrib), block.block.adminimal_theme_breadcrumbs (adminimal_theme), block.block.bartik_account_menu (bartik), block.block.seven_breadcrumbs (seven) in Drupal\Core\Config\UnmetDependenciesException::create() (line 98 of core/lib/Drupal/Core/Config/UnmetDependenciesException.php).

Drupal\Core\Config\UnmetDependenciesException::create('bsd_showcase', Array) (Line: 509)
Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module', 'bsd_showcase') (Line: 132)
Drupal\Core\ProxyClass\Config\ConfigInstaller->checkConfigurationToInstall('module', 'bsd_showcase') (Line: 161)
Drupal\Core\Extension\ModuleInstaller->install(Array, ) (Line: 83)
Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array, ) (Line: 1644)
install_install_profile(Array) (Line: 702)
install_run_task(Array, Array) (Line: 577)
install_run_tasks(Array, NULL) (Line: 117)
install_drupal(Object) (Line: 44)

Even if i delete the concerned config file in the above error log, new ones are named after a new installation attempt.The only difference is that version 2 have more module enabled, thus i suppose the problem come from there, do you know modules that cause problem at installation profile? Can you give me any hint, i am out of idea where to search...

Here is the list of modules of my profile.

name: 'bsd showcase'
type: profile
description: 'bsd showcase description'
core: 8.x
distribution:
  name: 'bsd showcase'
  langcode: en
install:
  - admin_toolbar
  - admin_toolbar_tools
  - adminimal_admin_toolbar
  - allowed_formats
  - autogrow
  - automated_cron
  - backup_migrate
  - big_pipe
  - block
  - block_content
  - book
  - breakpoint
  - ckeditor
  - ckeditor_abbreviation
  - ckeditor_codemirror
  - ckeditor_details
  - ckeditor_iframe
  - ckeditor_quote
  - ckeditor_specialchars
  - ckeditor_templates
  - ckeditor_templates_ui
  - ckwordcount
  - color
  - colorbutton
  - comment
  - config
  - contact
  - content_moderation
  - contextual
  - crop
  - ctools
  - datetime
  - dblog
  - default_content
  - default_content_set
  - devel
  - devel_generate
  - diff
  - dynamic_page_cache
  - editor
  - entity_reference_revisions
  - fakeobjects
  - feeds
  - field
  - field_ui
  - file
  - filter
  - focal_point
  - form_placeholder
  - hal
  - help
  - history
  - honeypot
  - image
  - layout_builder
  - layout_discovery
  - link
  - linkit
  - matomo
  - media
  - media_library
  - menu_ui
  - metatag
  - metatag_facebook
  - metatag_open_graph
  - metatag_twitter_cards
  - nbsp
  - node
  - notification
  - options
  - page_cache
  - panelbutton
  - path
  - path_alias
  - quickedit
  - rdf
  - redirect_after_login
  - responsive_image
  - search
  - serialization
  - settings_tray
  - shortcut
  - statistics
  - syslog
  - system
  - taxonomy
  - telephone
  - text
  - token
  - toolbar
  - tour
  - tracker
  - update
  - user
  - video_embed_field
  - views_bulk_operations
  - views_infinite_scroll
  - views_ui
  - workflows
  - forum
  - menu_link_content
  - pathauto
  - views
  - paragraphs
theme:
  - stable
  - classy
  - bartik
  - seven
  - adminimal_theme
  - bootstrap_for_drupal_distrib


texts: I want to make a curl request to an specific url, which will return an xml response. My question is, is there any drupal module which will take the input from interface and create a view for the response like SharePoint Module?


texts: Rebuilding or regenerating the teaser after changing the trim length in Drupal 7?

texts:
I changed the teaser length from 600 characters to 300 characters for the Story and Book Page content types. How do I rebuild the teasers so that all teasers are updated to the new value?

Any help would be appreciated.


texts:
I have this code in a custom module used to send an email through Mimemail

  if (!isset($message['headers'])) $message['headers'] = array('From' => $from, 'Sender' => variable_get('site_name', 'Drupal'), 'Return-Path' => variable_get('site_mail', ini_get('sendmail_from')));
  if (!isset($message['key'])) $message['key'] = array();
    $message = mimemail_prepare_message($message);
    $result = mimemail_mailengine('send', $message);
    if ($result) {
      drupal_set_message(t('Mailing sent sucessfully'));
    }
    else {
      drupal_set_message(t('Mailing not sent'), 'error');
    }
}

It works fine on my local MAMP enviorment, and on my Dreamhost VPS, but when I try to run on Media Temple a dedicated virtual box running Ubuntu, it does not work. I get my error message "Mailing not sent"

drupal_mail_system works fine


texts:
I am looking at a fairly complex problem (at least, so i think ;-))

I am working on a larger project that has ECK entities in a layout like this:

Project Entity (Has an entity reference to Article)
Article Entity (Has an entity reference to Article option AND has Dimension fields (width, height, ...))
Article option entity

Article option contains price and quantity information.

For example:

Article option "Pickup" has a price value of 1$ and a quantity of "per piece"
Article option "Installation" has a price value of 25$ and a quantity of "per hour"
Article option "Assemble" has a price value of 50$ and a quantity of "running meters" (with means that this has to be calculated)

Each project entity can contain references to multiple article entities, each containing references to multiple article option entities

We have a basic view that show all the articles of a specific project (through a contextual filter) and the options associated with each article.

Now the client is requesting to extend this view with a price line (in the view) per article option that is associated with each article in the project

So for example:

Article A has options Install and Assemble

Then the client would like these options to be visible in the view with their calculated prices AND unit prices.

It is important to understand that we need to save the calculated values for later use in the project as well.

I was thinking on creating an additional entity like this:

Entity Reference (unlimited values) to article options
Entity Reference to Article entity (1value)
Text field (unit price)
Text field Amount (optional for "running meters" calculations)
Text field calculated price

But this hardly seems like a nice way to do this.

All good ideas are very welcome!

Thanks so much in advance!

If any additional explanation is needed, feel free to ask!

Best regards


texts: how to react on file save using rules module

texts: How is it possible to react on newly uploaded file with rules? Is there any trigger like file upload or file update? Thank you.


texts:
In my experience Authcache gives a great enhancement to performance, however I am wondering what are the potential vulnerabilities using authcache and boost together? My worry is that when the administrator does not exclude user specific paths in boost configs, a saavy user can somehow access to other users' cookies and do nasty things.

I guess it is not just a hypothesis, as I've seen that at least in one occasion in a boost+authcache+varnish arrangement a user reported that others have sent message on her part without her knowledge. If this indicate a real security hole, how should one counter int? Which paths should be absolutely excluded from being cached by boost?

What other potential security holes can be in this setting and how to avoid them?


texts: How to set shorter caching time for a paragraph

texts:
I have made a paragraph that shows social media wall (based on PHP Social Stream-module). The problem is that the wall isn't updated except when the global cache is recycled.

I have tried (in vain so far) to find out what is the correct way to make the caching "more agile" for that paragraph.

The paragraph is only using the paragraph twig and a a small MYTHEME_preprocess_paragraph__PARAGRAPH_NAME-function.

As it is placed on the front page on a site under quite a heavy load, I would prefer it not to be un-caching the whole page (not even talking about whole site).

Any suggestions?

wbr

hank


texts: How to add programmatically region's class when region had block in D8?

texts:
I have one row three column region. How can I add custom class on each region when one of region is not work?

When three regiosn work, classes will be below

|------------|-------------|--------------|
|            |             |              |
|  region 1  |   region 2  |    region 3  |
|            |             |              |
|------------|-------------|--------------|
  col-sm-4      col-sm-4       col-sm-4

When two regions work, classes will be below

|-------------------|---------------------|
|                   |                     |
|  region 1         |     region 2        |
|                   |                     |
|-------------------|---------------------|
      col-sm-6             col-sm6

When only one region work, class will be below

|-----------------------------------------|
|                                         |
|               region 1                  |
|                                         |
|-----------------------------------------|
               col-sm-12

I use in page.html.twig like below. It worked for me but not good code for more column.

{% if page.region_1 and page.region_2 %}

 {{ page.region_1 }}

 {{ page.region_2 }}

{% endif %}

{% if not page.region_1 and page.region_2 %}

 {{ page.region_2 }}

{% endif %}

{% if not page.region_2 and page.region_1 %}

 {{ page.region_1 }}

{% endif %}

I'm try using hook_preprocess_region() like below. Can I check regions condition in hook_preprocess_region?

function MYTHEME_preprocess_region(&$variables) {

  // Add class in header region.
  $region = $variables['elements']['#region'];
  $region_header = array(
    'region_1',
    'region_2',
    'region_3'
  );

  if (in_array($region, $region_header)) {
    $variables['attributes']['class'][] = 'col-sm-12';
  }

}


texts: Use hook_views_pre_render() to change field to url link

texts:
I want to use hook_views_pre_render() to read in a view and change a field output to a clickable link.

Here is code:

function sbn_views_pre_render(ViewExecutable $view) {
    // https://drupal.stackexchange.com/questions/272495/how-to-get-views-field-names-values-for-hook-views-pre-render
    if ($view->id() == 'find_paragraphs') {
      foreach ($view->result as $key => $value) {
        $parent_id_value =  $value->_entity->parent_id->getValue()[0]['value'];
        $parent_type_value =  $value->_entity->parent_type->getValue()[0]['value'];
        $private_files = $value->_entity->field_private_files->getValue()[0]['value'];
        if ($parent_type_value == 'node') {
          $link = ''.$parent_id_value.'';
          // $value->_entity->set('parent_id', $link);
        }
        if ($parent_type_value == 'paragraph') {
        }
      }
    }
}

Formatting the $link value using standard html coding does not work.  Any ideas on how to format the link from within this hook so that the rendered field is a clickable link?


texts: website dont save /update content and any setting

texts:
I am develop in my laptop a drupal 7 on this enviroment: Windows 7 + IIS 7 + MSSQL Server 2008 R2 , its run fine. But when we upload to the webserver (Windows Server R8 + IIS 7 + MSSQL Server 2008 R2) and restore a backup of the database. The website don't save / update content and any change of settings for modules, site configuration, etc.. Drupal dont show error and the php log dont show warnings.

If you know about we can resolve this issue, please help me.


texts: What is the minimum I need to get a test for a module on D7?

texts:
I have a custom module that's fairly mature and I'm just now getting around to writing tests for it. However, I'm having difficulty getting the it to show up in the tests menu. What is the bare minimum that I need to get automated testing going for my module?

I have:

module.info:

files[] = tests/module.test

tests/module.test:

<?php
class ModuleTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module Test',
      'description' => 'Automated testing of Module.',
      'group' => 'Module',
    );
    function testModule() {
      $this->assertTrue(TRUE, 'Tests are working');
    }
  }
}

I've even set up a bogus test module that's basically what's outlined above, and it works. But my module with all my functionality it in won't show its tests on the test menu. So I'm trying to see if there's anything simple I'm overlooking.

Does the test file have to be called module.test or can it be called anything.test? Does the name of the class have to be ModuleTestCase or can it be arbitrary? I do have my files called module.test and the class called ModuleTestCase. I've also run the module.test on the command line php to test for syntax errors and I get none. What could I be overlooking?


texts: how should i send data form my custom module to a php file after submitting?

texts:
I have a Drupal form like this:

    function myblock_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

      return drupal_get_form('my_module_my_form');
 }

 function my_module_my_form($form_state) {
      $form['name']['price'] = array(
        '#type' => 'textfield',
        '#title' => t('price:'),
        '#value' =>t('100'),
        '#size' => 6,
        '#field_suffix' => t('$'),
        '#disabled' => TRUE,
      );
      $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
      );
      return $form;
 }

And i have submit function:

function my_module_my_form_submit($form, &$form_state) {

 $form_state['redirect'] = 'result.php';
}

My problem: how can i get $form_state['values']['price'] inside result.php? or in another way: how should i sent my data to a normal php file?
I studied several similar questions but didn't get my answer!
one suggestion was storing data in database which is not proper for my module! another suggestion was using sessions which i couldn't manage it(between module and php file)!


texts:
I am using Drupal 7, with the Stability theme. I'm trying to add featured products block to my home page but couldn't. I am able to add them to other pages, though.

How can I add or delete the front page's blocks?


texts: Is it possible to change the value of the field based on the the browser's language?

texts:
On my Drupal 8 website I have a content type "Video" which has an "Embed Code" field. Later the user is able to watch the video inside the platform. The value for this field usually looks like this:

<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/some_link" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Is there a way to change the source link based on the language of the browser? So for example when the user browser's language is set to "FR", then I would like to append to the emded link the french captions, so that the link looks following ?

https://www.youtube-nocookie.com/embed/some_link?cc_load_policy=1&cc_lang_pref=fr


texts: How do I pass a context filter to a block loaded by ajax?

texts:
There is a block created in views that displays the values of the taxonomy term fields.
This block should be loaded when selecting a term from the select field in a custom form. Accordingly, the block needs to somehow pass the tid of the term selected in the form.
The Select field in the form is formed as follows:
$form['rq_program'] = array(
       '#type' => 'select',
       '#title' => t('Program'),
       '#options' => GetProgramNameArray(),
       '#required'=> TRUE,
       '#ajax' => array(
          'callback' => 'GetTermInfo',
          'wrapper' => 'form-ajax-content',
          'method' => 'html',
          'effect' => 'fade',
        ),
    );

callback function:
function GetTermInfo($form, $form_state) {
    $tid=taxonomy_term_load($form_state['values']['rq_program']); //value from select

    $block = block_load('views', 'views_program_block');
    $content = _block_get_renderable_array(_block_render_blocks(array($block)));
    $output = drupal_render($content);
    return render($output);
}

I can't understand how to pass $tid to the block, how to set up a context filter in this block to receive this $tid?


texts:
So, this may be a stupid question because it seems pretty basic to me, but I can't find any information about this on here or elsewhere. Is it possible to specify fields to be visible/invisible to RESTful requests in Drupal 8? I would expect that this should be possible to configure--or, at the least, that fields hidden from the display would not be accessible via such requests.

Is this possible, or is there something that I'm simply not understanding here?


texts: How can I add jQuery to DOM element through drupal.behaviours?

texts:
On my site on the navigation panel I have a dropdown language switcher. (Dropdown Language Switcher module). I need to modify the js file and show the message to the user after he switched the language. What is the right way to modify js file?

(function ($, Drupal) {
'use strict';

Drupal.behaviors.dropdownLanguagesSelector = {
  attach: function(context, settings) {
   $('.dropdown-language-item .active-language', context).once('dropdown-language-selector')
    .click(function(e) {
      var $wrapper = $(this).closest('.dropbutton-wrapper');
      if ($wrapper.length > 0) {
        e.preventDefault();
        e.stopPropagation();
        $wrapper.toggleClass('open');
      }
    });
  }
};
})(jQuery, Drupal);

Language switcher HTML looks like following:

   FR

I am trying to attach following event:

$('.secondary-action').click(function(){
   alert(Message!);
})


texts: How to delete by bulk URL redirects for a specific content type?

texts:
For a content node say "foo1" I would like to delete all URL redirects. How to do this?

I tried views but do not get the node type in the relation. I can find several answers which updates url aliases (path auto module) but all these solutions do not delete the url redirects from redirects module.

Any solution is more then welcome. Whatever form is rules, programming...


texts: display question content type and a referenced node answer

texts:
I have a content type - question (its used for questions)
AND content type - answer (it has a field -> nodereference to questions with select list)

How to display in a view block question title and below to each question - referenced node title of content type answer?

What i did: i'v created a view block, and filtering it by content type - question, now im displaying all question titles, but how to display answers below these question (Each answer below referenced question)

Something like:

Do you smoke cigarettes?

Yes, i do.

What's your name?

My name's Jack.


texts: Display the size and format of a file attached to an article

texts:
I'm trying to display the format and size of a file attached to an article. Its system name is field_file.

So far, I've succeeded to load an article in my my_theme.theme file and the field_file field attached to it:

$article = Node::load($article_nid);
$variables['file'] = $article->get('field_file');

then use its uri in a twig file:
{{file_url(file.entity.fileuri)}}

Now I'm trying to display its format and size. I tried {{file.entity.format}} and {{file.entity.filesize}} without success.

Does anyone have a clue how to do it? I'm still new to Drupal plugins and entities.


texts: Can you duplicate a Drupal 7 site and database when a new user registers?

texts:
I'm building a site that will be used as a template site for new users. Once someone signs up, they should receive a copy of the original master template site, including their own SQL database.

Ideally, the new sub-site would need to receive updates from the master site somehow.

Is there a way to copy and entire site when someone registers? Can this be accomplished with Multi-sites?


texts:
I have created field type "Timestamp" in my Drupal 8 node. Field is not required. In field settings default value, there is HTML 5 datetime picker, in which you can select default date/time or leave values as on picture:

But the Drupal behavior seem to be little bit strange - when you select default date, this value is set on node save (this is correct). When you leave field blank (values as on picture) it saves field with time of form submission (it is stated in field comment, so it is not a bug)... But how to disable default value, when you just want to leave field blank as it is possible with all other fields (e.g. text, number, ...)? I do not see any settings for this in this field configuration. Also this is not logical, beucase when you leave other fields blank, they are really blank. When you leave this field type blank, it still saves value (some additional checkbox will be more logical)?

Thanks


texts:
I want to have reusable images in my new Drupal 8 blog.

I followed this guide that uses the Media Entity and Media Entity Image   modules, but I have a problem every time I want to use an existing image. I get the following error.

  The referenced entity (media: 206) does not exist.

So far, I used the default field_image field in the articles, but now I want to use the new field_reusable_image that uses existing images.

Will the already uploaded images in field_image be available to be added in field_reusable_image?


texts: I have a situation I want to put (*) instead of "required" word inside the place holder of a webform field is it possible from webform admin.


texts:
I want to disable user accounts programmatically inside hook_cron() after a synchronisation job. I don't want to delete the users because of their generated content. But they should not be able to log in and receive any notification-mails and stuff like that.

Should I use the user status field for that? And if so should I use user_save to change this as I don't want drupal to send out mails to the users (via _user_mail_notify inside user_save) or just set the status fields inside the db? Are there any other hooks or functions that I would miss doing that?


texts:
I have an active site running drupal 5 with phpbb2 for the forums.
QUESTIONS

Is Drupal 7 capable of supporting this forum functionality (or most of it)?
What would be a recommended upgrade path to reach that goal?
What modules would be necessary or recommended?


texts:
I tried to read a bit about what is actually a Variant in Drupal (and especially in Ctools).

But the 2-3 explanations I read were not clear enough for me. It was a wired experience for me since I've already learnt some "similar" Drupal unique terms such as Drupal argument, Contexual filter, Page (Drupal), Entity, Node, etc.

So what is a Variant and why do we need them? Please use the simplest explanation you can.


texts:
I tried to copy my site to a new sever and since id did that, I get an HTTP-Fehler 500 (Internal Server Error): on certain pages. The log files are reporting:

PHP Fatal error:  Call to undefined function chdir() in /var/customers/webs/something/includes/bootstrap.inc on line 3384
PHP Fatal error:  Call to undefined function max() in /var/customers/webs/something/includes/lock.inc on line 106

I cleared all caches many times with:

drush cc all

and also flushed the cache tables directly with MySQL commands. I disabled APC. I don't think, that this is a problem with the server, because it serves well for other Durpal sites.

EDIT: Here are my php.ini and htaccess.


texts: Invert shipping rate position with VAT field

texts:
As described in this post I'd like to invert the row between shipping service and VAT calculation.

I don't know how to use that hook... Can someone tells me more?

Thanks!

EDIT:
I followed the example.
I created the module, it's active and running but I see that nothing happens.

I tell you what I did (it's all in italian):
 - Created posizione_iva.info file with this content

core = "7.x"
description = "Modulo che sposta la riga dell'IVA dopo tutti i valori imponibili."
name = "Posizione IVA"

Created posizione_iva.module and copied the function

I have a doubt about this condition  if (substr($name, 0, 3) == 'iva')
Where can I find the right component name? I tried vat, VAT, iva, tax...

I use the default Drupal Commerce Kickstart installation and the "tax" module.


texts:
Fatal error: Unsupported operand types in `includes/theme.inc on line 980`

In my homepage im getting that error. I have no idea why I keep getting that error.

I'm on the process of upgrading my Drupal 6 to Drupal 7.

Thanks


texts: Unauthorized : CSRF validation failed issue for Logged in user

texts:
I need to hide button for Logged in user. For that I have written the following code in dashboard.js file.

Code working fine for anonymous user. But not working for Logged in user.

$(document).on("pageshow","#user_login",function(){
      try {
            $.ajax({
              url: "example.com/?q=drupalgap/system/connect.json",
              type: 'post',
              dataType: 'json',
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('page_dashboard - failed to system connect');
                console.log(JSON.stringify(XMLHttpRequest));
                console.log(JSON.stringify(textStatus));
                console.log(JSON.stringify(errorThrown));
              },
              success: function (data) {
                var drupal_user = data.user;
                //console.log(data);
                if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
                alert(drupal_user.uid);
                }
                else { // user is logged in, hide the login button, show the logout button
                  alert(drupal_user.uid);
                }
              }
            });

      } //try end
      catch (error) { alert("page_dashboard - " + error); }
    });

For logged in user getting popup like : .


texts:
I'm working with my college on a drupal website. However, we're both logged in as Admin, but I can't open these tabs.

He says he has no problem with it and told me it could be a Java problem. I reinstalled Java and checked in mutiple browsers, but I still can't open them. Do you guys have any clue why?
I run on windows 8.1, I have the latest Java and Flash installed.
Thanks in advance.


texts: Is it possible to define a field as disabled on creation in field_create_instance?

texts: I have a content type that has a mix of user-editable fields and auto-populated fields (from an external source). I would like to mark those fields as disabled right when I create them so the user cannot overwrite them. I know there are readonly modules and ways to do this in hook_form_alter but I'm curious if I can short circuit having to do this on the fly and just have it disabled by default. Thanks.


texts: Accessing values of unknown field types when using entity_metadata_wrapper

texts:
I've been looking into using the Entity Metadata Wrapper classes (defined by the entity module in Drupal 7) to access field values, as this seems to be a clean way of doing so.

There a couple of things that make this a bit awkward however. Assume I have a wrapper for a content type that defines a field named field_something as such:

$wrapper = entity_metadata_wrapper('node', node_load($nid));
$value = $wrapper->field_something->value();

The first problem I have is that I have no way of knowing before hand whether what I get is an actual value (a string, an entity, etc.), another metadata structure wrapper (when fields have multiple values) or an array (when fields have multiple properties).

I have found a way to answer those questions using the info() method:

$info = $wrapper->field_something->info();
$is_multi_value = (strpos($info['type'], 'list<') === 0);
$has_multiple_properties = isset($info['property info']]);

However that is hardly practical. Whenever I want to use a field without knowing it's definition before hand, I must take into account several cases. This makes my code quite heavy.

In order to deal with this I have written some code which:

Ensures we always get returned an array, even if it's a single value field ;
When there are multiple properties, return the value of the first column.

Point 1. here will always work, unless the caller want to know whether this was a single value field or not. Point 2 works in some cases, not all, but is convenient when it applies.

Here is the code:

function entity_metadata_simple_values($field) {
  $fields = array();
  $values = array();
  $info = $field->info();
  if (strpos($info['type'], 'list<') === 0) {
    foreach ($field->getIterator() as $field_iteration) {
      $fields[] = $field_iteration;
    }
  } else {
    $fields[] = $field;
  }
  foreach ($fields as $final_field) {
    $ff_info = $final_field->info();
    if (isset($ff_info['property info'])) {
      $column = reset(array_keys($ff_info['property info']));
      $values[] = $final_field->{$column}->value();
    } else {
      $values[] = $final_field->value();
    }
  }

  return $values;
}

So my question is: are there simpler/better ways to address this problem of getting values from the metadata wrapper when the field type is not known ?


texts:
I am trying to implement Justified-Gallery: http://miromannino.github.io/Justified-Gallery/ in my Drupal 7 website.

I linked justifiedGallery.min.css and jquery.justifiedGallery.min.js.

The thumbs are generated with Node Gallery module.

In my script.js I call

Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {
    $('.gallery').justifiedGallery();
  }
};

but on the page only the loading animation shows, the divs holding the thumbs remain with opacity:0 and are not arranged in grid... Interestingly all elements are assigned the respective styles by the script, so I think the script is not kicking-in properly.

I also tried putting

 $(document).ready(function(){
    $('.gallery').justifiedGallery();
 });

but again no luck...

Both codes are wrapped in the

(function ($, Drupal, window, document, undefined) {
...
})(jQuery, Drupal, this, this.document);

What am I doing wrong? Any help appreciated.


texts: Show only user related activity in a heartbeat view

texts:
How do I create a heartbeat activity that shows only user related activity? For example, user 1 is related to user 2 and 3 (user relation module). When user 1 is logged in, he should be able to see activity only from user 2 and 3 and not from other users; similarly, it should happen for user 2 and 3. I'm logging the activity using the heartbeat_api_log() function.

UPDATE

The orthodox method of achieving this is to use hook_heartbeat_related_uids().

It works fine, but in order to fine tune according to your own customizations you might want to use hook_heartbeat_load(), and remove unnecessary messages based on a condition you specify.


texts:
I am trying to figure out which template file is used in a page and I stumbled upon this variable to enable in the setting.php

$conf['theme_debug'] = TRUE;

I did enable the variable in the settings.php and in default.settings.php (what is the difference actually?), but with no luck on seeing the generated output in the markup. And of course cleared the caches several times.

So am I really blind to the generated output? Where does it actually generates?


texts: How can I have custom content as last page?

texts:
I have a view which shows nodes of 3 specific content types. The content shown is coming from the parent node with entity reference fields where the nodes can be selected to be shown in the view.
I was wondering how I could add custom content, or maybe a node to the end of a that view without having to select it on the parent, because this is always the same content.
What I want is like have the view display a node or some programmatically custom content. It should be there as last page. For example I have a view with 4 nodes, the pager should show 5 and have the 5th page be the node/content I want. I don't want to have to add it every time on the parent node with the entity reference field. It should be there by default.


texts: Instructive message when a module is disabled accidentally

texts:
Site breaks without a warning when code of a non-enabled module is called.
(In my project I disabled accidentally a module, while the code is executed by another module.)

The correct way is to add dependencies, but sometimes that is forgotten (and rather old-fashioned). PHP Storm does not check whether a module is active or not; it just validates the call.

Is there a way to get a message when code of a non-enabled module is called?


texts: Add conditional redirect to Views exposed filter (using BEF)

texts:
I have a view showing a select list of locations. Upon selecting a location the View shows a Google Map with the locations of the current selection.

For certain items in the select list I would like to redirect away from the View to another page.

I have looked at these discussions:

https://www.drupal.org/node/1379492#comment-6273188

How to change programmatically exposed filters in views

But none of them mentions my specific case of conditional redirection.

Any clues very welcome!


texts: Order Total not updating after I change the line item price

texts:
I have a custom form which on submit creates a new order, loads a product and a custom line item type. I then save the information from the form in the line item. The line item price is updated via a rule which calls a custom PHP function. The problem is when I redirect to checkout/order_id the Order Total is not updated.

I've tried altering the order directly using my order_wrapper and i've also tried using commerce_price_component_add. I tried a rule which called "Save entity" again but nothing seems to be working.

Can somebody give me a point in the right direction on how to get the order total to re-calculate.

Also if anyone has any good examples of creating orders using custom line item types from a custom form that may be helpful


texts: Custom RESTful api GET request only works if user is already logged in, although _access has been set to 'TRUE'

texts: Controller outputs a json response. On local machine it works fine weather user is logged in or not. But on the server if the use is not logged in to drupal the single page application that fetches unpublished nodes using ajax call gets 503 (Service Unavailable) error. I have done what this link says and set _access: 'TRUE' in the routing.yml file and tried couple of other things but no luck. Any idea what could be the cause?


texts: How to replace a string in a URL field when outputting it in a template file

texts:
I created a new field for URL. What would the best way to replace certain strings in the URL when outputting the field into the field--field_url.tpl.php file be?

For example, in http://example.com/master/m/ I need to remove the "http://" part, and replace master with slave.

It is a single field; there will be no foreach() loops.

==== edit after using preprocess ===
i got a undefined index: field_url

with the devel i get this

field_url
   und
     0
       value

i put in the preprocess

$link = $variables['field_url'][LANGUAGE_NONE][0]['value'];

$link = str_replace('http://', "", $link);

$link = str_replace('master', 'slave', $link);

$variables['link'] = $link;

is this right?

====== entire hook =======

function lessxless_preprocess_field(&$variables)
{
    $link = $variables['field_url'][LANGUAGE_NONE][0]['value']; // grab value

    $link = str_replace('https://', "", $link); // trim http://

    $link = str_replace('master', 'slave', $link);

    $variables['link'] = $link;
}

sites/all/themes/lessxless/template.php


texts: Set data value of entity reference field with rules

texts:
Is there a way that you can "Set data value" of an entity reference field using rules. So I would like to set a newly created node's entity reference field to another node's entity reference field.

Thank you in advance!


texts: Panelizer: displaying node reference field

texts:
I have an "Event" content type with a node reference field of type "Host".

"Host" content type has an "Affiliation" field.

I would like to display the event details though Panelizer, so that it would show not only the host name, but also their affiliation. How can I access a node reference field through panelizer?

My guess is that it should be done though the "Existing Node" option, but I might be wrong.


texts: Close the iframe after login with Shadowbox module

texts:
I have installed the Shadowbox module and I use it to show the login page in a pop-up iframe.

The problem is when I click on the sign-in form submit button the iframe still appears and the page refreshing inside the iframe is not the original page.

How can I close the iframe after login and make the page reload?

The Ajax error is the following:

  An AJAX HTTP error occurred.
  HTTP Result Code: 200
  Debugging information follows.
  Path: /arabdc/system/ajax
  StatusText: parser error
  ResponseText:
  parent.window.location.reload(true);[ {"command":"settings","settings":{"basePath":"\u002Farabdc\u002F", "pathPrefix":"", "ajaxPageState":{"theme":"bartik", "theme_token":"PQ_SrF6skDNUXCQNOJJg54EPuosNo0QM5sX6fr2Sfko"}, "heartbeat_language":"ar", "heartbeat_poll_url":"http:\u002F\u002Flocalhost:8888\u002Farabdc\u002Fheartbeat\u002Fjs\u002Fpoll", "shadowbox":{"animate":0, "animateFade":0, "animSequence":"wh", "auto_enable_all_images":0, "auto_gallery":0, "autoplayMovies":true, "continuous":0, "counterLimit":"10", "counterType":"default", "displayCounter":1, "displayNav":1, "enableKeys":1, "fadeDuration":"0.35", "handleOversize":"resize", "handleUnsupported":"link", "initialHeight":160, "initialWidth":320, "language":"ar", "modal":false, "overlayColor":"#000", "overlayOpacity":"0.85", "resizeDuration":"0.35", "showMovieControls":1, "slideshowDelay":"0", "viewportPadding":20, "useSizzle":0}, "custom_search":{"form_target":"_self", "solr":0}}, "merge":true}, {"command":"invoke", "selector":null, "method":"myJavascriptFunction", "arguments":[  ]}, {"command":"insert", "method":"prepend", "selector":"head", "data":"\u003Cstyle type=\u0022text\u002Fcss\u0022 media=\u0022all\u0022\u003E@import url(\u0022http:\u002F\u002Flocalhost:8888\u002Farabdc\u002Fsites\u002Fdefault\u002Ffiles\u002Ffontyourface\u002Ffont.css?mmj0o1\u0022);\u000A@import url(\u0022http:\u002F\u002Flocalhost:8888\u002Farabdc\u002Fsites\u002Fdefault\u002Ffiles\u002Ffontyourface\u002Flocal_fonts\u002Fmyride-normal-normal\u002Fstylesheet.css?mmj0o1\u0022);\u003C\u002Fstyle\u003E\u000A", "settings":null} ]


texts: How do I properly pass values from PHP to JavaScript?

texts:
I am currently writing a module and I am trying to pass some variables to the Drupal.settings.

My module uses the following code.

function bcc_preprocess_views_view(&$vars) {
    drupal_add_js(array('modulname' => array('key' => 'value')), 'setting');
    drupal_add_js(drupal_get_path('module', 'modulname') .'/script.js');
}

The script.js content is the following.

(function ($) {
    console.log(Drupal.settings.modulname);
})( jQuery );

The output I find in the log is undefined, but when I check the content of  Drupal.settings.modulname from the browser, it gives me the desired value.

When I add this code, the log shows the right values.

drupal_add_js('jQuery(document).ready(function({console.log(Drupal.settings.royal)});', 'inline');

What is wrong with that? What is the correct code to use?


texts:
Is it possible to select fields for the export?

For example: When i click button it shows me a popup, where i can select content i want to attach to the exported file.


texts: Using another html.tpl.php for specific page

texts:
I have googled this alot but none of the suggestions I found works for me.

I want to use another html.tpl.php template for a specific page, preferably matched with the url-string to that page, but the id works aswell.

This is the code I'm trying now (in template.php):

function mytheme_preprocess_html(&$variables) {

    $nid = arg(1);

    if ($nid == '1715') {
        $vars['theme_hook_suggestions'][] = 'html__test';
        echo "testing testing";
    }
}

My custom template file is named: html--test.tpl.php.

The echo part does print on the page so the $nid is correct.

mytheme is not the actual name of my theme, but I replaced it here.


texts:
I've two api url

/api/v1/get-list
/api/v1/post-item

In API url /api/v1/get-list I was set cache like this:

$build = [
  '#cache' => [
    'contexts' => ['url','url.query_args'],
    'max-age' => 3600,
  ],
];

$res = new ResourceResponse($response, 200);
$cache_metadata = CacheableMetadata::createFromRenderArray($build);
$res->addCacheableDependency($cache_metadata);

Response will be cache in one hour with url /api/v1/get-list?_format=josn. When I use api /api/v1/post-item response of /api/v1/get-list will changed value. But response was cached in one hour. So how to trigger delete cache of url when use orther url. I find some code

\Drupal::service('page_cache_kill_switch')->trigger();

but just for current request.


texts: Use Rules to notify original author when their node is published

texts:
In short, I'm simply looking to notify the original author when their node goes from a non-published state to a published state. I have Workbench Moderation enabled if it makes a difference.

I've tried implementing the exact solution that was provided / accepted here (https://drupal.stackexchange.com/a/159103/79465) but can't get it to work for some reason.

Solved for with the following config:


texts:
I am attempting to sanitize my database as described in this Acquia guide.

For my site, I need to sanitize all the usernames as well; I would like to sanitize the usernames exactly the same as the e-mail addresses.

The guide suggests using a hook such as this:

<?php
/**
* Implementation of hook_drush_sql_sync_sanitize().
*/
function modulename_drush_sql_sync_sanitize($source) {
    $query = "UPDATE content_type_profile SET field_primary_email_email = CONCAT(SUBSTRING_INDEX(field_primary_email_email,'@', 1), '@example.com');";

    $query .= "UPDATE content_type_profile SET field_work_phone_value = SUBSTRING(FLOOR(RAND() * 1000000000000) WHERE uid NOT IN  SELECT uid FROM users_roles WHERE rid=3) AND uid > 0 FROM 1 FOR 12)  WHERE field_work_phone_value IS NOT NULL;";

   drush_sql_register_post_sync_op('my-sanitize-id', dt('Sanitize email addresses and phone numbers'), $query);
}
?>

But since this is for Drush, I don't know where to put the hook.  I tried modifying the code and  adding it to an enabled module on my site, but when I ran sql-sanitize, it didn't pick up the hook.

This is what I did.  In MYMODULE/MYMODULE.module, I added the following code:

/**
* Implementation of hook_drush_sql_sync_sanitize().
*/
function MYMODULE_drush_sql_sync_sanitize($source) {
    $query = "UPDATE user SET name = CONCAT(SUBSTRING_INDEX(name,'@', 1), '@example.com');";

   drush_sql_register_post_sync_op('my-sanitize-id', dt('Sanitize user names'), $query);
}
?>


texts: is it possible to add a permission to only one user , without creating role for him?

texts:
i'm trying to create drupal 7 module for online payment , it will be by roles , for exemple ( user1 can create 'Blog content type' just if he has the permission on that) so after the payment i want to add that role to that user so i can avoid the each time creating roles for the users

thanks ^_^


texts: How to check condition and print a value using views-view-field--viewname.tpl.php?

texts:
I'm having a view and I've created a template file for the row style output.
I'm able to access the fields using the below code:

$fields: An array of $field objects. Each one contains:
$field->content: The output of the field.
$field->raw: The raw data for the field, if it exists. This is NOT output safe.

I'm getting output for the below code:

<?php print $fields['field_some_field_name']->content; ?>

But when I'm trying to print the fields nothing is getting returned:

<?php print_r($fields); ?>

I'm also unable to check the condition for the fields:

<?php if($fields['field_some_field_name']->content == 'Test') { } ?>


texts: Show all values of a multi File field sorted by upload time

texts:
I have a content type with a File field that allows multiple values. What's the best way to display these files as a list ordered by upload time rather than delta but still using the file descriptions?

The Manage Display options don't really give any options for sorting the list on the node display.

I tried creating a File View using the content id in the url as a contextual filter, while this does let me sort by date I can't seem to use the file description in the output.

Is there a way to get file descriptions in File views or should I look at writing a custom formatter for the node display?


texts: Trying to understand caching when data is dynamic?

texts:
I have a content type with a field called: "secretword".

When viewing the page, I have logic in the tpl.php file that determines if this field is going to be shown to the user. The logic for whether it must be shown is quite complex (calls a web server, calls another, does a calc etc, so having roles for each condition doesn't make sense). My concern is that if I calculate the field in the tpl page, that somehow somewhere along the line the page is going to be cached. Or perhaps indexed in the search directory for prying eyes to find.

So I need:

any user to access a node
each user to see a guaranteed new version of the page with their personally calculated "Secretword", including in search results etc
no cached values for these nodes ever for any prying eyes to find

How can I display nodes securely, knowing that the data on the page won't be cached and will remain well-hidden in search results?

UPDATE

Would setting up a rule that if you access content not passing a certain PHP condition, forwards that user to a access denied page?


texts:
this is what the module has in it now for basic toggle of the login box.

   Drupal.logintoboggan_toggleboggan = function() {
  $("#toboggan-login-link").click(
    function () {
      $("#toboggan-login").slideToggle("fast");
      this.blur();
      return false;
    }
  );
};

I hacked the module's js file to this to get the function i needed but i dont want to have to do that if there is a better way.

Drupal.logintoboggan_toggleboggan = function() {
  $("#toboggan-login-link").click(
    function () {
      $("#toboggan-login").slideToggle("slow", function() {
         if($(this).css('display') == 'block'){
                 $("#art-main").append('

');
                     $(".outer-login").click( function () {
                          $("#toboggan-login").slideToggle("fast");
                          $(this).remove();
                     });
      } else{
          $(".outer-login").remove();
      }
      });

      this.blur();
      return false;
    }
  );

I have tried unset for the logintoboggan module but that didnt seem to work.


texts: Easiest way to test email notifications locally?

texts:
I am making a forum website with email notifications. I need to test these email notifications locally. Ive only ever used MAMP so I dont have much experience setting up dev environments.

What's the easiest way to test Drupal's email notifications locally?  Can the Acquia stack do this?