texts: Block visitors based on geographic location conditionally in .htaccess on multi-site install

texts:
I have a Drupal 6 multi-site install that runs numerous different websites for a single instance of Drupal. These web sites attract worldwide traffic which is what my client wants, with one exception.

One of the sites attracts lots of visitors from Italy, which my client doesn't want as it creates problems for them. As I result of this I would like to block visitors from Italy visiting the site by blocking them based on IP addresses (note that I already have the IP addresses and the method of blocking the visitors). The way I want to block the visitors is in the .htaccess file like so:

<Limit GET HEAD POST>
order deny,allow
deny from 2.16.70.0/23
deny from 2.19.16.0/20
etc...
allow from all
</Limit>

My issue is that if I put that code into my .htaccess file, it will block visitors from Italy visiting each of the websites in the multi-site install, which I don't want. I simply want to block them on a particular website, perhaps based on the URL or something. Can anyone point me in the right direction?


texts: Change the sorting order used for Book nodes

texts:
How can I change the order used for Book nodes, which by default is based on weight and title?

I have a set of nodes displayed inside a page that use a structured book. I want to display them ordered by weight and random, instead of weight and name.

The book is used to structure different types of local companies and restaurants.

I have traced the code looking for a solution, but it's a bit messy for me.

Is there a hook that could be helpful to achieve this?


texts: I would like to disable user access to the administration during updates, such as bugfixes and additions of new content-types etc. I'm not completly sure on how to achive this. What would be the best solution, setting the site in maintaince mode is not an option.


texts: How to get taxonomy image and path by tid in Drupal 7?

texts:
I want to get categiries image and path in Catalog Block for Ubercart 3 (Drupal 7) which is taxonomies. I know only tid.

For path i try this

$tid = (int)$variables['catid']; // return tid
$term = taxonomy_term_load($tid);
print_r(entity_uri('node', $term));

but site crashed.


texts:
How can I get a list of all the fields that have been attached to a taxonomy vocabulary?

I have created 2 new fields using admin/structure/taxonomy/[machinename]/fields now I need to get all the fields and use them on a settings form. I have the vocabulary machine name, but how do I retrieve all fields created?


texts: How can I calculate product price based on product attributes?

texts:
I would like to calculate prices for all of my products based on value of the length or weight attribute multiplied by price per meter/g of the material selected for the product.

What is the best way to do this?

I have created content type material which has price per unit attribute. Each product when created is a assigned a material and length/weight.

When I tried to use the pricing rules i discovered I can only do simple things to the existing price and not calculate a brand new price :(

Once I have solution to this I want to be able to allow the user to select the weight/length and for the price to update accordingly.

Best Regards, Atta


texts: comments not available for Support Ticketing System

texts:
i have a strange problem, i installed  Support Ticketing System module, enabled Support module and Support Overview, created support client, give AUTHENTICATED USER Can select client and Access Support tickets permissions. Then when a test user issued a new support ticket i couldn't comment it although comments are enabled from content type! and the user are the same, actually there are now place for the comment block!

what i expect is when an user opens a support ticket the reply for this ticket will be via comments, so it suppose to have comment available for the ticket.

Any help will be appreciated


texts: Php libchart with value from my custom table

texts:
I want select value from my custom table where there are tweets saved.
I have the column for the counter of retweets and I want the sum of the count hourly for 24 hour.

I write this code:

$time = time();
$prev_date = date('d-m-Y H:i:s', $time);

$dataSet = new XYSeriesDataSet();

foreach($req as $val){
 $serie = new XYDataSet();
 $val_id = (int)substr((string)$val, 0, strpos((string)$val, "-"));

    for($i=23; $i>=0; $i--){
        $next_date= date('d-m-Y H:i:s', $time - 3600*$i);
        $prev_date= date('d-m-Y H:i:s', $time - 3600*($i+1));
        $next_date = mysql_real_escape_string(trim($next_date));
        $prev_date = mysql_real_escape_string(trim($prev_date));
        /*$weight_q = db_query("SELECT SUM(`retweetCount` + `favoriteCount`)/2 as peso
                        FROM  `ax_twitter`
                        WHERE (`date` BETWEEN '{$prev_date}' AND '{$next_date}') AND (`ID_request` = %d)", $val_id);
        */
        $weight_q = db_query( "SELECT SUM(`retweetCount`) as peso FROM `ax_twitter` WHERE (`date` BETWEEN '$prev_date' AND '$next_date') AND (`ID_request` = %d)", $prev_date, $next_date, $val_id);

        while($row= db_fetch_object($weight_q)){
            echo($row->peso);
            $serie ->addPoint(new Point($next_date, $row->peso));
        }
        $prev_date = $next_date;
    }
$dataSet-> addSerie($val, $serie);

}
$chart->setDataSet($dataSet);

$chart->setTitle("Andamento dei Retweet e Favorite");
$chart->getPlot()->setGraphCaptionRatio(0.8);
$chart->render($path_image);

}

I tried different ways with query sql but I have the following errors:

  warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '18:39:52 AND 01-10-2014 19:39:52) AND (ID_request = 1)' at line 1 query: SELECT SUM(retweetCount) as peso FROM ax_twitter WHERE (date BETWEEN 01-10-2014 18:39:52 AND 01-10-2014 19:39:52) AND (ID_request = 1) in trigger_error() (line 134 of C:\xampp\htdocs\drupal\includes\database.mysqli.inc). =>

When I added the quotes to the parameters of the sql query , however do not get any results for my graph. My question: is right way?...is right query?
With PHPAdmin I get right results if set two dates manually
sorry for the language.


texts: My custom module does not show persian or arabic texts!

texts:
I am developing a custom module. When I try to use Persian or Arabic text it does not show the text properly! The texts are shown in black square.
should I add anything?

As you see I installed Farsi language and menus are in Farsi but my custom text in module is not shown!


texts: SQLSTATE[42000]: Syntax error or access violation in drupal views query

texts:
When trying to preview a view containing references to three Field Collection module fields, I get the following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS node_, node.created AS node_created, 'field_collection_item' AS field_data_fi' at line 1

Here is the full attempted query:

SELECT field_collection_item_field_data_field_obit_service.item_id AS field_collection_item_field_data_field_obit_service_item_id, node. AS node_, node.created AS node_created, 'field_collection_item' AS field_data_field_service_location_field_collection_item_enti, 'field_collection_item' AS field_data_field_service_time_field_collection_item_entity_t, '' AS field_data_field_service_type__entity_type
FROM
{node} node
LEFT JOIN {field_data_field_obit_service} field_data_field_obit_service ON node.nid = field_data_field_obit_service.entity_id AND (field_data_field_obit_service.entity_type = 'node' AND field_data_field_obit_service.deleted = '0')
INNER JOIN {field_collection_item} field_collection_item_field_data_field_obit_service ON field_data_field_obit_service.field_obit_service_value = field_collection_item_field_data_field_obit_service.item_id
WHERE (( (node.status = '1') ))
ORDER BY node_created DESC
LIMIT 5 OFFSET 0

I don't know sql that well, but it appears as though some of the references are being truncated due to length. Also there is a reference to an empty string ('') as a column name. Any idea what's wrong and how to correct it?


texts: how to change the widget of view's exposed filter form?

texts:
I have an exposed filter form, and its default widgets are textfields. I'd like to change them to selects based on values from database.
I have tried hook_form_alter and hook_form_views_exposed_form_alter, but get an error:

An illegal choice has been detected. Please contact the site administrator.

The code I used to change the widget is like this and I've tried #validate option.

$form['field_address_province'] = array(
        '#type' => 'select',
        '#options' => $province_options,
        '#validate' => true,
        '#description' => 'Select address',
    );

Edit:

Sorry for the lack of infomation.
The $province_options is an array like

Array
(
    [0] => Please Select
    [6] => Area1
    [7] => Area2
    [2] => Area3
)


texts: Unknown drupal_view() function although Twig Tweak is installed

texts:
Acquia BLT won't let me commit some Twig.
> tests:twig:lint:all
Validating twig syntax for all custom modules and themes...
Iterating over fileset files.twig...
  ERROR  in ~/repos/agency/client-site/docroot/themes/custom/client_theme/templates/taxonomy/taxonomy-term--faq.html.twig (line 35)
      33       {{ title_suffix }}
      34       <div class="accordion" data-accordion>
  >>  35         {{ drupal_view('faqs_per_term', 'block_1', term.id) }}
  >> Unknown "drupal_view" function.
      36       </div>
      37     </div>
 [WARNING] 28 Twig files have valid syntax and 1 contain errors.

I have installed and enabled Twig Tweak module, and rebuilt cache.
Do you know of any reason why BLT might not know the module is installed?
Possibly relevant: I'm running Drupal and BLT under Lando. The error is triggered after git push but I get the same result if I call lando blt tests:twig:lint:all directly.


texts: page which display only $content (no header,footer,sidebars)

texts:
I wanted to show a page which displays only $content. I successfully got the output when I used this code in template.php inside my theme.
function THEMENAME_preprocess_page(&$vars) {
  if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    $vars['template_file'] = 'page-ajax';
  }
}

In page-ajax.tpl.php, I used the following code.
<?php
  echo $content
?>

Is there anyway to achieve the same thing using a custom module?
update
I think you all misunderstood my question, i want to override page.tpl with only $content, Not how to create a tpl using hook_theme!
Currently i have used the same code in my module, but the problem is i have to manually copy page-ajax.tpl to my active theme directory. You can refer the module i created http://drupal.org/project/ajax_links_api


texts: Loading nodes from another Drupal database using Views

texts:
I'm trying to use Views to load nodes from another Drupal database defined in settings.php with a key of 'cms'. Both sites are Drupal 7. The other database is a different Drupal install which is acting as a content repository or centralized CMS. My goal is to create a new view type/group on the destination site, so when creating a view the site build can choose "CMS Content" instead of "Content". I'm hoping a site builder would then be able to build a view normally based on content types and content from the centralized CMS site, even if I have to tell views about all the fields in each content type.

In my hook_views_data() implementation I've set the 'database' key, but can't figure out how to read from the node table without overriding $data['node'].

function cms_connector_views_data() {
  $data['cms_connector']['table']['group'] = t('CMS Content');
  $data['cms_connector']['table']['base'] = array(
    'field' => 'nid',
    'title' => t('CMS Content'),
    'help' => t('Content from the centralized CMS.'),
    'database' => 'cms',
  );

  return $data;
}

Of course this doesn't look for a node table, it looks for a cms_connector table in my cms database, which doesn't exist.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cms.cms_connector' doesn't exist

http://views-help.doc.logrus.com/help/views/api-tables says that the key within $data…

  should be the actual database name of the table (not including
  prefix), but it can be an alias as long as the join information
  (explained later) contains the real name of the table.

I don't actually want to do a join, I want to create a base table from the other database's node table. But I tried this anyway (even though it doesn't really make sense) after seeing http://drupal.org/node/1713010#comment-6310438:

$data['cms_connector']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'left_table' => 'node',
    'field' => 'nid',
    'table' => 'node',
  ),
);

I've searched around here, d.o, and Stack Overflow, but most of what I'm finding is Some-other-database-to-Drupal, not Drupal-to-Drupal.

I found the https://drupal.stackexchange.com/questions/12736/using-nodes-from-another-site-database question here, but it's about node references, and is unanswered.

I thought about using Services to read XML/JSON from the centralized site, but there are too many hurdles to that approach. I don't really want to synchronize nodes either.


texts: Render React Components in Twig Templates

texts:
I am using React JS in my theme (installed via NPM), and exporting views using REST. I want to render the JSON view data into React components and call them in the twig templates.

The way I have it working now is I have js/main.js importing components eg: js/components/slider.jsx etc. The component files decide where to render. Eg:

ReactDOM.render(
  document.getElementById('elementid')
);

I have a gulp task running which bundles, transforms ES6 - ES5, and uglifies all the JS imported in js/main.js into js/script.js which is the only JS loading from the theme. I'm not sure if this is the best option for performance.

Maybe another option is to compile each component (ES6 must be transformed to ES5) into it's own JS file and define them as libraries, which can be then called in the twig templates?

I have tried to use TwigReactDirective but I get errors following the instructions.

Are there better options / ways of doing this?


texts: Showing a node edit page with drupal_get_form() and hook_menu()

texts:
I am using drupal 7 and am stuck at a very basic problem. I would like to simply show the edit page to a known node id. I know there are similar posts but they either didn't work or I didn't understand theme.
My module looks like this:

<?php
/*
 * Show the edid page to a specific nid.
 */

function control_center_menu() {
  $items = array();
  module_load_include('inc', 'node', 'node.pages');
  $nid = '4';
  $node = node_load($nid);
  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_node_form', $node),
    'access callback' => TRUE,
  );
  return $items;
}

However, at test/test I get a bunch of errors:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of /home/christian/workspace/gigs/includes/form.inc).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /home/christian/workspace/gigs/modules/menu/menu.module).

And instead of the hole form I only get the Menu setting check box and the URL path settings.

What am I doing wrong? I tried hard to find a noob friendly copy past example but didn't find any... Thanks a lot in advance!


texts:
I've recently inherited an Drupal 8 website.  www.berkslibraries.org  At the bottom of the site in the footer there is the word Contact and under it a link to Hours & Locations, email address, and a phone number.  I have searched through Drupal and can't find where that information in stored to change it.  It's not in the content section or in the custom blocks.  I was hoping someone might have some advice on where I can possibly look to change that info.

Thanks,


texts: How to get the count of referenced entity (by views entityreference result)?

texts:
For example, a student can register a class. The class node has a date field indicating whether the class is active for registering. The registration node has an entityreference field referencing to the class node. I get the referencing class nodes by using "Views: Filter by an entity reference view" option. This view has a filter of "current date is between the start and the end date". Now, if the count of the reference view result rows is 0, the student should be redirected from the node/add/registration page to an explanation page which tells students there is currently no active classes for registering.
On the module entityreference_count page, it says,

  Currently this module only works with entityreference fields
  configured to use the "Simple (with optional filter by bundle)"
  option. It does not work with the "Views: Filter by an entity
  reference view" option. This may be addressed in a future release.

How can I make it?


texts: How can I add a constraint to a custom field I created?

texts:
I have created a complex field type (my class extends DateRangeItem) that supports recurring dates by adding a property for storing an RRULE string:

class DateTimeRecurItem extends DateRangeItem {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['rrule_string'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('RRule String'))
      ->setRequired(FALSE);

    return $properties;
  }

  ...

I want to validate the RRule string (there's a RFC to validate it against). I can do this by creating a custom constraint and applying it like this:

$properties['rrule_string'] = DataDefinition::create('string')
  ->setLabel(new TranslatableMarkup('RRule String'))
  ->setConstraint('MyCustomConstraint')
  ->setRequired(FALSE);

The problem is I also need to know the value for the value property of the field (which is inherited by DateRangeItem). Implemented as above, my constraint validator will only be passed the raw string value of the rrule_string property.

I can't figure out how I can define a constraint that applies to the entire field (thereby having access to all of its field properties). There seems to be no interface for doing that.

To be clear, this is not a field I've added to a custom entity definition. This is just a custom field I defined that can be added to any entity.


texts: Adding target _blank to ajax form based on response

texts:
I have been pulling my hair out on this for a few days now, and I cannot seem to actually execute something as simple as this successfully on submission of my form.

What I am trying to do is this... If I fill out my form and it passes validation and the ajax response is sold on click, I would like the form to go to /success and open a new tab/window that goes to google.com else just go to the failed page

It's simple I know. The problem is this, that when I do click it and have a new window/tab come up, the pop up window blocks it. This tells me that this method isnt really a valid method of clicking the button.

This is what I have as my form
.module

    function storageform($form, &$form_state){

        $form['first_name'] = array(
            '#type'  => 'textfield',
            '#title' => t('First Name'),
            '#required' => TRUE,
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
            '#ajax' => array(
                'callback' => 'storage_form_ajax_callback',
            ),
            '#attached' => array(
                'js' => array(
                drupal_get_path('module', 'storage_form') . '/storage_redirect.js' => array(
                'scope' => 'footer',
            ),
         ),
      ),
    );

        if(isset($form_state['values'])){
            $form['page_output'] = array(
            '#markup' => storagedb_submit($form, $form_state)
            );
        }
        return $form;
    }

    /**
     ** Form Ajax
     **/
function storage_form_ajax_callback($form, $form_state) {

      $receipt_info = 'sold';

$commands = array();
      $commands[] = ajax_command_remove('div.messages');
      $commands[] = ajax_command_before('#main', theme('status_messages'));

    if(!form_get_errors()){
      $commands[] = array(
        // The command will be used in JavaScript file
        'command' => 'storage_redirect',
        // JavaScript function:
        'itemstatus' => $receipt_info,
    );

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

    function storage_form_ajax_callback_validate($form, $form_state){

        if($form_state['values']['first_name'] == ''){
            form_set_error('first_name', t('First name required.'));
        }
    }

storage_redirect.js

    (function($){
    Drupal.ajax.prototype.commands.payday_redirect = function(ajax, response, status){
                if(response.leadstatus == 'sold'){
document.location.replace("http://localhost/storageform/thanks");
window.open('http://www.google.com','_blank');
                    }else{
document.location.replace("http://localhost/storageform/failed");
                }
        }
    }(jQuery, Drupal));

Please someone help me with this small nightmare of a problem I am having.
Thank you.


texts: How to display Meta tag description for Views genereated page

texts:
How to display meta tag description for Views generated page. Title is displaying by views but not description. Even I entered in Views description PFA.

Along with that I tried "Metatag Views Overview" module that gives an error when I created new meta tag.


texts:
I am using simplenews for my newsletter and mime mail to send them by mail.

I am trying to use the same CSS for my newsletter mail than my newsletter displayed on the web site.

Is it possible to refere the same css file?


texts: How do I update the body of a node using a query?

texts:
Let us consider I have a node called "DrupalTest" for which I need to update the body content using AJAX.

Shall I execute a query, or is there any other way to update the body content?


texts:
In the logs (Drupal 7), I have seen the next entry (I have edited some compromised info). It seems a failed (only I hope it actually failed) attempt to access the login account. I have tried to replicate the error, but cannot have the same error entry with failed login/password, so I am very worried that it originated in some possible breach of Drupal 7 security.

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
'Crap' AND status = 1' at line 1: SELECT * FROM {users} WHERE name = :name_0, :name_1 AND status = 1; Array ( [:name_0] => FcUk
 [:name_1] => Crap )
in user_login_authenticate_validate() (line xxxx of /[HOME_ROOT]/[PUBLIC_HTML_PATH]modules/user/user.module).


texts: Where can I find good, reliable Drupal freelancers?

texts: I've looked on Elance, Guru, etc for skilled, reliable Drupal freelancers without any luck.  Are there any suggestions for where to look for these folks?  Remote workers are fine for what I need done.


texts: How to create a Rules action set to calculate a sum of integers in a Field Collection?

texts:
I'm having a Field Collection 'My List' with two fields: 'Amount' (integer) and 'Date' (date). I often count the 'Amount' items with Rules like this:

Add a variable: Parameter: Type: Integer, Value: 0, Provides
variables: Sum
Loop over [node:field-my-list]

Calculate a value: Parameter: Input value 1: [sum], Input value 2: [my-list:field-amount], Provides variables: Result (result)
Set a data value: Parameter: Data: [sum], Value: [result]

As setting up this loop every time takes quite some time, I thought that creating a Rules component (action set) would make things a lot easier. I tried this:

Data type: List of field collection item items, Label: List, Usage: Parameter.
Data type: Integer, Label: Sum, Usage: Provided.

Creating a loop (Parameter: List: [list], List item: Current list item (list_item)) works, but there's a problem when I try to calculate the value "Sum + List:item". Namely, I can only select list:0, list:1, list:2 and list:3 as "List:item". That doesn't seem to be right.

How can I correctly select an item from the list and use it in the calculation?


texts:
by default, front and none path is defined in the system.routing.yml file and it's '/'.

But me, this value is sync with one of my view path.

For exemple, in my page view "Xyz", if the path is "/x-y-z, the  path setted in the database router table is /x-y-z. if i change it to /abc, after clearing cache the value in the database will be /abc.

If i delete the Xyz view, it will automatically sync the path value with an other view path.

I don't know why and i don't want that, i want it stay what the system.routing.yml file defined : "/". there isn't other front route definition in any file, in my theme or in some module.


texts: How to save a checkbox config_object in the schema files?

texts:
We have a custom module with the following files. It is mainly used to store a list of content types that this configuration applies to. When saving the configuration, we get the following code.

How do we properly set the mymodule.schema.yml file to save the checkboxes?

Error Message. We also get the error message if we select Basic Page from the configuration.

  The website encountered an unexpected error. Please try again
  later.InvalidArgumentException:
  The configuration property mymodule_enabled_content_types.article
  doesn't exist. in Drupal\Core\Config\Schema\ArrayElement->get()
  (line 76 of core\lib\Drupal\Core\Config\Schema\ArrayElement.php).
  Drupal\Core\Config\StorableConfigBase->castValue('mymodule_enabled_content_types.article
  ', 'article ') (Line: 211)

mymodule/config/schema/mymodule.schema.yml

mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: string
      label: 'Enabled Content types'

mymodule/config/install/mymodule.settings.yml

mymodule_enabled_content_types: ''

mymoduleForm.php

...
public function buildForm(array $form, FormStateInterface $form_state) {
  $config->$this->config('mymodule.settings');
  // Get all Content Types.
  $types = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->loadMultiple();

  foreach($types as $type) {
    $content_types[$type->id()] = $type->label();
  }
  $form['mymodule_enabled_content_types'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Enabled Content Types'),
    '#description' => $this->t('Define what content types will be enabled.'),
    '#default_value' => $config->get('mymodule_custom_variable'),
    '#options' => $content_types,
  ];
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration
    $this->configFactory->getEditable('mymodule.settings')
      ->set('mymodule_enabled_content_types', $form_state->getValue('mymodule_enabled_content_types'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}
...


texts: How do I add the number of rows shown in a view to a menu link?

texts:
I want to add the number of rows shown in a view to a menu link, something as follows, for example.

  Companies(29) | Products(152) | Customers(522) | Orders(9888) ..

How can I achieve this?


texts: Why is the jquery_update module not supporting the latest jQuery version?

texts:
The recommended jquery_update module only supports 1.10. Why recent jQuery security version 3.4.1 not updated?
https://jquery.com/download/

So is it recommended to make my Drupal site to update with latest jQuery version for security reasons?

When I try to make the module to support latest jquery version, I am facing issues with other jQuery UI files. What are the additional UI files need to be addressed to work with latest jQuery version?

Thanks,


texts: How to access current amount of earned userpoints in a Rules Condition?

texts:
I have no access from Rules to [points] field or any userpoints field (User points module).

I have enabled: Rules, Rules scheduled, Rules_ui, Userpoints, Userponints_rules_integration, Userpoints_role (from userpoints_contrib),

I have done un/installed several times one by one modules mentioned with clear cache and cron in between and nothing, no access to userponits fields.

My event is "before saving content", in the Rules Conditions I have "User has a role-->auth-user", also in Rules Conditions I have "content is of type-->My custom contentype" in that order (I have changed that order with no results).

I need to update userponits field value before (preferred) or after a node is saved.

I tried also via Rules Components with an element "User has a role-->auth-user", same thing: no access to Userpoints fields.

I have another rule applied and reacting on Rules Event: “After saving a new user account” and there YES I have access to those fields.

Any ideas? Reference module? Do I have to implement a hook in template file to load current user? Do I need a custom module? I've seen all the node.one screencasts about Rules several times. And I have read many post in here, and (think) I’ve done everything right, but no success.

Any suggestions?

In case that your suggestions are: hook or module (I’m not a skilled programmer) please submit some code within.


texts: Show block on specific pages URL attribute

texts:
I am looking to show a certain block on a page only when a certain url attribute (using alias)

For example:

I have pages /foo/*

I want to show the The block when viewing /foo/*?showblock

Where * is a wildcard.

I have tried typing this into my "Show block on specific pages" portion of the block settings, but the block never shows. Any ideas? Thanks!


texts: Hide errors from users but show to admin?

texts: Under 'Error messages to display' I can hide errors (as is recommended for production sites). However is it possible to hide errors for everyone except a certain role?


texts: Shipping/Delivery Labels in Drupal Commerce

texts:
I've been searching for a way to print shipping/delivery labels for Drupal Commerce (drupal 7 kickstart). I'm amazed that there still seems to be no real solution to this but rather a series of hacks. I was sure this would be adequately covered or even be part of core! We could do this in Ubercart and yet it seems to have been overlooked in Drupal Commerce.

Anyway, we want to be able to print the labels to a label printer as we process each order from the admin screen. The closest 'solution' is this Print mailing address labels from a view. This isn't exactly ideal as we just need a button next to 'Shipping Address' which prints the label to the label printer.

Using the Themer Devel module it tells us we should be able to override commerce-order--backoffice.tpl.php where we were hoping to inject a print code and customise the print fields using the Print Module http://drupal.org/project/print but drupal refused to see our version of commerce-order--backoffice.tpl.php.

We just seem to be going around and around with this one trying idea after idea getting nowhere, very frustrating that this has been overlooked by Drupal Commerce.

Any ideas much appreciated.
Chris


texts: Customized User Registration form with Profile fields

texts:
I'm missing something core to how user registration forms are customized and the data is added to the database and I'm hoping to get a workflow.

I have created about a dozen Profile fields, textareas, radio buttons, select lists, etc.

I have written a module to do a form_alter, and in that module I have laid out fieldsets and containers so that everything is neat and orderly.  For example, for Home Information I have this:

$form['hi'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => t('Home Information'),
    );

    $form['hi']['hic'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',

    );

    $form['hi']['hic']['left'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',

    );

    $form['hi']['hic']['right'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'container',

    );

and then I have this to display Profile fields that are relevent to Home Information:

$form['hi']['hic']['right']['profile_memberlist']['field_home_phone'] = $form['profile_memberlist']['field_home_phone'];
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#maxlength'] = 16;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#size'] = 13;
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#title'] = t('Phone');
$form['hi']['hic']['right']['profile_memberlist']['field_home_phone']['#description'] = t('Enter your phone number');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name'] = $form['profile_memberlist']['field_first_name'];
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#maxlength'] = 16;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#size'] = 13;
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#title'] = t('First Name YO');
$form['hi']['hic']['left']['profile_memberlist']['field_first_name']['#description'] = 'HEY THERE';

Now when I view the registration form, I see first all my generic Profile fields, PLUS the elements created from the above. I thought that unsetting the profile_memberlist was the way to go, but it turns out that while the user is created the Profile fields do not get saved this way.

My Submit is something like this:

$form['#submit'][] ='all_data_form_submit';

the actual function:

function all_data_form_submit($form, &$form_state) {
drupal_set_message('
' . print_r($form_state['values'],TRUE) . '
');

$new_user = array(
'name' => $form_state['values']['name'],
'pass' => user_password(),
'mail' => $form_state['values']['mail'],
'init' => $form_state['values']['mail'],
'status' => 0,
'access' => REQUEST_TIME,
  'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
  'field_last_name' =>  array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),

);

$form_state['redirect'] = array(
'node/31890',

array(
  'query' => array(
    'foo' => 'bar',
  ),
  'fragment' => 'baz',
 ),
);

$account = user_save(null,$new_user);

}

But that ends with a DATA INTEGRITY error on submit, because apparently user_save is being called twice?  I remove the user_save and the user is created, but none of the Profile fields get added to the database.

What has worked for me is when both the unstyled and the styled form elements are shown, and I don't use a custom submit handler, the Profile data is saved.

My question: how do I display the styled and neatly organized form elements only, and have the data entered through them get saved to the database?


texts: How to hide a field in a comment in hook_comment_view programatically?

texts:
My comments have a field called 'Extra'. I'm trying to hide it when the user who's viewing the comment wrote it. This is my custom module:

function mymodule_comment_view($comment) {
  global $user;
  if ($comment->uid == $user->uid){
    unset ($comment->field_extra);
  }
}

Why isn't this working and what's the correct way to achieve my goal?


texts: How to filter Date Views with correctly timezone

texts:
I am using latest Drupal 8.2.5 for Live-score website. I have the Views for display all games daily. It's including DateTime for schedule and storing on Europe/London timezone (by default).

On the views FILTER CRITERIA, I added Match_Date_Fields between:

Today
+1 day

For getting the matchs from today events and next events.
So, the views will filter by default timezone (london), sure. But when the visitor access to my site from Thailand. This filter seem to wrong. Because here difference between timezone from London to Thailand.

For example: The game is play on "January 15, 2017 19:45" for London timezone, but from Thailand it's "January 16, 2017 02:45".

I made it successfully print with depends on the local's time zone. But have no idea How to filter with correctly local's timezone?


texts: How to stop webform from sending an email

texts:
I'm using Drupal 7.12 / Webform 3

How do I stop email from being sent upon a webform submission? I want to do this conditionally so I need to use a hook. I still want everything else to go through correctly (i.e. confirmation page, db entry for submission).

I see that there are these lines in function webform_client_form_submit($form, &$form_state)

if (!$is_draft && !$form_state['values']['details']['finished']) {
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);
    webform_submission_send_mail($node, $submission);
  }

How do I hook into that and stop it?


texts: Warning message and URLs not found on menu items

texts:
My question is in relation to a Mamp issue Im having.

Installed Mamp on my MacBook, loaded the database off my live Drupal 7 site, downloaded and copied the Drupal files on the live site to Mamp htdocs, changed the Drupal config settings (db, host, user, password) to use Mamp site, but it displays the home page, with the warning messages below, and if you click on any menu item it displays URL not found. Any ideas what Im doing wrong?

Ive tried using the latest Drupal 7 core, and also using the same Drupal files as the live site, but I get the same result.

Warning message on Home page:

Warning: "continue" targeting switch is equivalent to "break".
Did you      mean to use "continue 2"? in require_once()
(line 341 of  /Applications/MAMP/htdocs/rltc/includes/module.inc).


texts:
I have worked in Drupal projects where SASS was used to generate CSS files in a theme (with gulp or compass).

I have also worked in Drupal projects where a lot of the CSS (without SASS) was living in custom modules, to style Drupal components (views plugins, ds layouts, field formatters, etc).

I am now wondering what would be the best way to combine both worlds:

Have SASS sources distributed in distinct (custom module) directories, and some in the theme.
Allow to include sources from other modules. Of course dependencies must be declared accordingly.
Allow contrib modules, or "corporate" modules that are meant to be reused, to ship with SASS sources.
Watch the entire tree with gulp or compass, without watching the toplevel dir.
Generate the CSS files in a common directory, or in distinct directories, I don't care that much.
Have some way to control which generated CSS file is included on a page.

The main limitation of SASS seems to be that it is limited to one directory, where you keep all the source files and that you watch with gulp or compass, and one output directory for the finished CSS files(s). At least this seems to be how it is commonly used. This is not ideal if I want to distribute the CSS across module directories.

For now the question is quite open-ended, perhaps someone already did this and can describe a workflow / architecture.

Platform

The project I am asking this for is currently on D7, but will move to D8 soon. I would be interested in both, but will mark it as "8", and hope I can then apply a similar technique to D7.

Theme CSS vs module CSS?

Some developers have quite strong opinions about the location of CSS files, accepting only the theme as a valid place for anything front-end related. You are free to share such opinions, but please don't make this the only part of the answer!

Is this a Drupal question?

Perhaps the individual technical obstacles are not specific to Drupal. But my use case is, and I am hoping that someone else had a similar scenario.


texts: How can I include user pictures in e-mail notifications sent by the privatemsg module?

texts:
I have the Private Message module configured to send notifications when users receive a private message.  I have the Mime Mail module configured and working; the private messages are sent as HTML and display properly.  However, I have been unable to find a way to include user pictures in the messages.

On my site, I have a field that contains the user picture (I am not using the standard user pictures built-in to Drupal).  However, I have overridden the user pictures template to show this field, so a solution that works for user pictures should hopefully work for my case as well.

I tried to solve this with tokens.

The token module makes available the following token: [privatemsg_message:author:field_acc_profile_picture]

However, when I include this token in the message, it is simply returned as a text string; no substitution is performed.

I thought this could be done with PHP but there is no way as far as I can tell to include PHP in the e-mail notify message field.

So, how can I include user pictures in e-mail notifications sent by the privatemsg module?


texts: How to handle files for Drupal in cloud when in multi-site mode?

texts:
I want to run Drupal from a cloud and I am trying to figure out the design of the file system for multi-site setup.

In cloud there are multiple webservers hidden under the load balancer serving content from a single database(which is a service that handles replication on its own so no issue there) and using central storage for user/drupal data.

So far I have solved the user-added data(mostly images uploaded into a content or attached via fields) but I'm stuck on how to handle files like compiled Twig templates, config directory, services file and settings file and similar.

Once a new web server instance is created it will fetch the code from git repository. The user data is handled via stream wrapper(and cdn) so no action is needed there. But how should I handle the system(yml, php..) files? The settings.php and services.yml are global so they won't change(still - how to handle this in multisite setup?) and the rest is dynamic(ie. once the cache is flushed the twig templates are recompiled and this needs to be synced for all instances).

The more static files like the settings.php and services.yml files could be potentially stored in some "remote" storage and fetched from there(ie. a directory tree matching the installed sites with these files already present - not a git repo though, I think that would not be a good idea) or they could be dynamically generated based on data stored in special database.

But what about the rest(twig, config...). Would something like a fast cache be a good design? Redis db that would hold the current files and each instance would either fetch them manually or serve them directly? Once an instance flushes cache this would be immediately "synced" to all instances in second scenario. For first scenario there would have to be some timestamp with latest change that each instance would have to check on each page load and re-fetch the files.

Drupal has this quite specific file system tree so that's why I'm asking this in here. I'm sure many people run Drupal in the cloud and I'm curious how they solved this "issue".


texts:
I have the panels module installed. So I have two types of pages:

Under the Create content/Page, the basic content type
Under Site Building/Pages/Add Custom Page, the page with panels

So, I've used the Panel pages all over the place and everything is easy; however, for a particular project, I have some content-types that were based off the basic Page (example 1 above).

I need to figure out how to add a view to that kind of page. There is a lot of HTML with jQuery setup to allow for a custom tab system on one page: Click on a tab and via show/hide the appropriate content shows up and adds a hash tag to the url for deep linking.

I'm guessing I will select PHP code for the input format, but I haven't found the right snippet to include a particular View within all the HTML code that is already there.

I tried to just use <?php print $content; ?> within the div for the last tab of content to see if I could get something to render but it didn't show anything so perhaps this isn't the right way anyway?

Some notes

My view has four displays and I need to call the one "ISO 14001 docs" but, the view has an argument of "(Document) Content: Link" so that is probably why I have not been successful.

I've tried the following code, but I'm not getting anything and I'm not sure how to add that type of argument in this kind of call.

$viewName = 'sc_file_view';
print views_embed_view($viewName);


texts: "No Drupal site found" -- Windows and SQL Server

texts:
So I'm trying to upgrade our system from using Drush 6 to Drush 8, as that is the currently supported version of Drush that supports Drupal 7. I have managed to get drush working, however it does not recognize any of our environments as a Drupal environment.
If I run drush cc all I get back:

No Drupal site found, only 'drush' cache was cleared.

If I run any other Drush command (from my sites directory) I get back:

Command 'command' needs a higher bootstrap level to run.

Running drush status returns no DB information at all.
Now there seems to be quite a few questions out there like this, and lots of recommended solutions, but nothing is pertinent to my environment. I'm using IIS on a Windows Server machine, with SQL Server (not MySQL), so none of the solutions are applicable. I'm wondering if anyone has any ideas for solving this within my current environment?

Keeping in mind, all of these environments worked fine with no issue prior to upgrading to Drush 8 (using Drush 6).
Output of drush -v status:
Loading outputformat engine.                                 [notice]
 PHP configuration      :  "C:\Program Files (x86)\PHP\5.6.26\php.ini"
 PHP OS                 :  WINNT
 Drush script           :  location/of/drush
 Drush version          :  8.1.13
 Drush temp directory   :  temp/location
 Drush configuration    :
 Drush alias files      :
Command dispatch complete                                    [notice]

settings.php file database settings:
$databases['default']['default'] = array(
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'hostName',
  'driver' => 'sqlsrv',
);

Executing drush sql-connect command returns:

Unable to load class Drush\Sql\Sql.
Unable to find matching SQL Class.
Drush cannot find your database connection details.

I should also mention that drush site-install works fine, it's just running Drush inside a newly created area that doesn't work.

To clarify, I am using a multi-tenant install, so I have multiple tenants such as sites/tenant, sites/tenant2, sites/tenant3, etc.
For example I am running drush from the sites/tenant directory and Drush doesn't recognise my Drupal installation. Traditionally, before updating, I could run drush from inside any of those and everything would work.


texts: Is there a module that can replace tabbed menus with contextual links?

texts:
The tabbed menus at the top of node with entries like View, Edit, Outline takes too much space for my liking. In my case I also use the Node Clone module which also takes up more space because it uses an action link.

Is there a module to hide the tabbed menu and expand it on demand, or change it to contextual links? I have seen a few examples but they all seem to require changes to existing theme files or modules. Is there one implemented as standalone module?


texts: How can I add value in drupal session. I am adding value using $_SESSION = 'my value', but once trying to print $_SESSION variable it return blank.


texts:
$query = db_select('watchdog', 'wa');
$query->join('distinct', 'di', 'di.wid == wa.wid')
  ->orderBy('wid')
  ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
  ->range(0, 20);
$result = $query->execute();

It shows me the error: Call to a member function orderBy() on a non-object in


texts:
What would be the proper hook to redirect after the user registration form is submitted and is in valid state?

I'm trying to automatically create a certain content-type node when a user registers and I want to redirect the user to that node's edit form after the user creation form is submitted and validated.

I was thinking of doing this in a mymodule_user_form_submit hook, but not sure if a) this hook exists and b) the validation in place for user registration will still work as intended.

Can anyone share some pointers?

EDIT:

Would the mymodule_user_insert hook run after the validation and submission of the form? Can I redirect from there? AFAIK, I won't have a form_state variable to act on, right?

EDIT2:

While researching for a solution, I noticed I have another (probably bigger) problem: the content-type node I need to create must hold a reference to the user's ID, so I'm getting in a chicken-or-egg situation.

I actually need to create said node after the user is created (otherwise I'll have no user_id), but I need to redirect to the node's edit form after user creation, which means I can't redirect with $form_state.

I think I got everything right, but I would love to be wrong. :D

Can anyone help?


texts: Drupal views - 2 latest reports and related content

texts:
My Drupal site contains a certain type of report, and these reports sometimes have 1 or more amendments, which will have field_related_content pointing to the report they're amending.

I'm trying to set up a view that will display the latest two reports, plus any amendments to those reports, but I haven't been able to figure out how to do it.

Can Views filters refer to results from other filters?


texts: Generate and email coupon code to customer after they purchase full price item

texts:
We have a situation where we want to be able to automate a process for certain customers to receive a discount coupon after making a purchase.

Ideally, customers could just throw two of whichever package they are purchasing into the cart and be good to go, but because of some oddities with our underlying product (a software package that they get access to for a few months) they need to make separate purchases if they need more than one license. And there are a few situations where we would want to provide a buy one get one half off coupon, but it's not every time.

I'm wondering if it's possible to create a condition of some sort, like a particular coupon code or product that we can provide to customers, that once they purchase an email is automatically sent with a 50% off your next purchase coupon.

I'm pretty new to working with Drupal and don't know where to start with this or if it's even possible.

edit: we are working in Drupal 7 and using ubercart

Thanks!


texts:
There is at least one other question dealing with this, but I found no satisfactory explanation, let alone a solution.

My site used to deliver 800x600 native images hosted externally that were scaled by the browser and CSS. To improve the Google Page Speed, my client asked me to ingest and serve the images on the Drupal site and to size them on the server.
So far, so good.

Now I am noticing a big degradation in quality - not good for a real estate site:

(this is slightly enlarged to better show the issue)

On the right is the old site with scaling/cropping done by Chrome from 800x600 down to 315x208, left is the new site with an image style using imagemagick set to 100% quality, doing the same size reduction and cropping. I tried the "resize" filter but that has the same issue and does not give me the desired results.

The images are not from a stale cache, the image field max size is 800x600, and the file on the server is unaltered and has the original size. It is definitely the image style filter that is causing this.

Previous recommendations were to increase the quality setting for the image toolkit (admin/config/media/image-toolkit), switch to imagemagick, and ensure that the max resolution of the image field does not cause scaling. I have done all that and don't see any improvement.

Any other suggestions?


texts: Get Post data of a view in inside a block

texts:
I am actualy tring to get the posted data from a views filter and display it inside a custom block.

This is what my code looks like for now

<?php
/**
 * Implements hook_block_info().
 */
function search_block_header_block_info(){
    $block['search_header'] = array(
        'info' => t('Search Header'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function search_block_header_block_view($block_key){
    $block = array();

    if($block_key == 'search_header'){ //We only want to define the content of OUR block

        dsm($_POST);
        //This is the title of the block.
        $block['subject'] = t('Search Header');
    }

    return $block;
}

But for some reason the $_POST variable is always empty. Someone got a hint for me how to get the posted data?


texts: Can trusted host settings use an IP address?

texts:
I'm working with a test site installed on a server on my network. Since it's only a sandbox, it has no domain name. Drupal being installed in a sub-directory (there are several sandboxes), I access it through an address like this: http://10.156.222.145/d8

However, when I put this in the trusted host patterns, like so:

$settings['trusted_host_patterns'] = array(
    '^10\.156\.222\.145\/d8$',
    '^localhost$'
  );

I get the error message: "The provided host name is not valid for this server."

Question: is it even possible to configure these settings with an IP address, and if so how?


texts:
I'm using the below code to query a webform field's value against database, and if the value exists, I want to use form_set_error, however I can't, since it requires rewriting the page. I have found this post but it doesn't have an answer, hence my question.

function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi']['#ajax'] = array(
        'event' => 'blur',
        'callback' => '_tubitekuz_check_username',
      );
      break;
    case 'contact_site_form':
      $form['#submit'] = array('_tubitekuz_show_message');
      break;
    default:
      break;
  }
}

function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    $commands = array();
    $commands[] = drupal_set_message('Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

How do I go about that?

PS: drupal_set_message does its thing only when I refresh the page, whereas form_set_error doesn't do at all.

EDIT: I tried to replace the above with the below code:

function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    drupal_add_js(drupal_get_path('module', 'tubitekuz') . '/js/tubitekuz.js');
    drupal_add_css(drupal_get_path('module', 'tubitekuz') . '/css/tubitekuz.css');
  }
}

and in tubitekuz.js I am doing

$(document).ready(function() {
    var username=jQuery('#edit-submitted-kullanici-adi');
    username.addClass('err');
    setTimeout(function() {
      username.removeClass('err');
      }, 3000);
});

and in tubitekuz.css I have the below:

.err {
  border-color:red;
  border-width:2px;
}

however, CSS rules are not applied even though class is added. What is the cause of this? All I'm trying to do is use form_set_error with #ajax


texts: Replace field label in content type template

texts:
I'm outputting fields in a template for my content type like so:

print render($content['group_details']['field_city']);

However, I would like to replace the default label that is attached to the 'city' field. I cannot alter the label in Drupal's content type so I'd really need to do so directly in the template. How can I instruct Drupal to hide the current label and replace it with a custom label in the content type template?


texts: Complex Shipping Rule: €3 Flat Rate for order's first 2kilos + extra €1.2/extra kilo charge

texts:
Well, the title is quite descriptive about what I'm trying to do with Rules for my e-shop.
I have a flat rate for shippable products and I want to charge extra shipping costs to customers according to order's total weight. I'm already using physical fields for weight so I could use the field's value for this rule. Note that some products won't have anything in the weight field and in this case I don't want to take them into consideration for the shipping cost calculation.

So, I want to charge €3 (flat rate's base charge) if the order is 0-2 kilos.
In case the total order's weight is more than 2 kilos, I want to add €1.2 to shipping cost for every additional kilo.

e.g. order has 3 products.
Product 1 - 2 kilos
Product 2 - 0 kilos (or no value in weight field)
Product 3 - 2.5 kilos
Total order's weight: 2+0+2.5 = 4.5 kilos (ie 2.5 kilos to be charged extra)

So the shipping charge should be €3 (flat rate's base) + €1.2*2.5 = €6.

I really need some guidance here on how I'm going to make this happen using Rules.


texts:
I have used LDAP module with Drupal 6 without issues, but now that I am working with Drupal 7 the LDAP module seems to be unable to load the AD groups. I have searched all along the web but I couldn't find any help.
The returned error on the watchdog simply states "unknown error: 6"

The complete watchdog row is:
ldap_authentication pippo.4 : Authentication result id=0 auth_result=6 (unknown error: 6)

The same authentication works fine using Drupal 6 + LDAP.
What could be wrong?


texts: How do I set field mapping in the Feeds module for Drupal 8?

texts:
I'm trying to use Feeds 8.x-3.x-dev on Drupal 8.4. I've created a feed type (eg. News Feed) and I'm trying to set the field mappings, but I get an empty list with no way to add anything to it:

The target content type is a custom one, that's similar to Articles, but it also contains some extra fields (such as the source of the feed).
If I add a feed URL to this type and try to import it, it obviously fails:

Test Source has been created.
Warning message
An entity of type "content" failed to validate with the following errors:
Title (title): This value should not be null.
News GUID (field_news_guid): This value should not be null.
News Link (field_news_link): This value should not be null.
News Source (field_news_source): This value should not be null.
Please check your mappings.
Error message
Failed importing 20 News.

Most tutorials and references online talk about the module for Drupal 7, which looks significantly different from what I see.
Is there something I'm missing or is this mapping feature currently broken?
Edit: I am aware of the pre-release status of this module, but I'm trying to evaluate it to see what works and what doesn't. Downgrading to Drupal 7 isn't an option, so I have to make do with what I have for 8. If not Feeds, is there any alternative for a simple RSS/Atom feed import? Aggregator would work just fine for my needs, but how do I get it to import the contents as nodes?
Edit: I decided to downgrade to Drupal 7.


texts:
In Drupal 7, I use the following code to print more than one view inside a block.

<?php print views_embed_view('view_name', 'display_name'); ?>

In Drupal 8, it doesn't work and it returns Array. Although the documentation for views_embed_view() says it's the same as in Drupal 7, it doesn't work in blocks using the PHP filter module.


texts:
Coder says:

The $message argument to watchdog() should NOT be enclosed within t(), so that it can be properly translated at display time.

Does this mean that $message will be translated by watchdog() by default?


texts: How do I pass the value entered for an entity field to strip_tags()?

texts:
In the module I am working on, I have an entity field defined with a call to BaseFieldDefinition::create('string'). I would like the user input of this field to be passed to strip_tags() or any equivalent Drupal function.

How would I grab the value submitted from users to pass it to that function?


texts:
My question is in the title, when i add a new element of entity "intervenant" I check, if there is already an intervenant with the name used in form_state, if the query returned me a result, i want to stop the insert into and be redirected in my front page.

I used return FALSE;

But it's didn't work.. You can see my code :

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'intervenant')
    ->fieldCondition('field_int_projett', 'target_id', $idProject, '=')
    ->fieldCondition('field_int_numero_lot', 'value', $lot, '=')
    ->fieldCondition('field_int_intervenants', 'target_id', $intervenant_id, '=')
    ->propertyCondition('status', 1);
$intervenant_externe_pjt = $query->execute();

if(!empty($intervenant_externe_pjt['node'])) {
    return FALSE;
}

How can i stop the submit, if it's possible ?

Thanks


texts: drush installing drupal through root ssh is causing 500 internal server error

texts:
I have installed the drupal 7 using the root ssh user. The overall installation process seems ok within ssh. I have even downloaded and enabled the modules through drush. But when I tried to open the site on browser its throwing 500 internal server error.

I used the same process with out any errors when I grant a jailed shell access to the hosting account and login through their cpanel id in ssh.

But for the ease I want to install drupal through root ssh so I don't have to open multiple putty windows to manage multiple accounts.


texts: How to use "taxonomy_get_childern" function

texts:
//TID of current loaded node

<?php
$nid = arg(1);
$tid1 = db_query("SELECT data.name,data.tid FROM field_data_field_books book
 INNER JOIN taxonomy_term_data data ON data.tid = book.field_books_tid
 WHERE book.entity_id = $nid ");

 foreach($tid1 as $t){
    print "Name ==> " . $t->name;
    print "Tid ===> " . $t->tid;
 }

 //function to load child term
 $child = taxonomy_get_children(32);
 foreach($child as $ch){
   print "Name===>" . $ch->name;

?>

my question is that I want load tid dynamically instead of hardcore value
I am using the above code in block please tell me how I am handle this situation?


texts: How to check if code is running inside simpletest?

texts:
Here's the best I've come up with so far:

/**
 * Returns TRUE if our code is running via a simpletest.
 *
 * We don't check for the database prefix so that this can be used by Unit
 * Tests also.
 *
 * We could set a variable in the test setUp method and check that variable,
 * but then some dummy could misuse that variable in code intended for
 * production.
 */
function check_is_simpletest() {
    return class_exists('DrupalTestCase', FALSE) || strpos($_SERVER['HTTP_USER_AGENT'], 'simpletest') === 0;
}

Is this crazy? I'd expect it to break in the Testing UI pages of the site, but I'm only concerned with testing custom code which will not affect those pages, and I usually test via drush.


texts: How do I create a site inside another one?

texts:
I have a Drupal site (example.com). There is some content, and there is a page at example.com/projects/abc.

What I want to do is create another site on example.com/projects/abc/NEWSITE.

How can I do that?

Normally, I can create folders via FTP such as projects->abc->NEWSITE, but there is content on example.com/projects example.com/projects/abc.


texts: How to programmatically add a facet to Facet API based on returned facet values?

texts:
I would like to programmatically and conditionally show a facet block, if the returned values match some certain criteria. I have not found any solutions so far.
For example, if a facet returns 25 apples, I would like to show an additional facet that does some calculation on this value.


texts: Expose filter in block to show results on view page

texts: I want to make custom search block on home page, in header region. I'm using Exposed filter block in Views module, but results on the page are shown just below the block, in header. I want results of the search to be shown on the other page, like regular search do. Is there a way to achieve this. I'm using Drupal 7.


texts: What path to images to use with CKEditor to insert images in content?

texts:
When putting images in content items, I have to put the full URL, otherwise images don't show up.

It works for this full path:

http://localhost/IT/sites/default/files/mypictures/apache_pb.png

But doesn't work for this path:

sites/default/files/mypictures/apache_pb.png

I know I must be missing something? A token? Variable to path?


texts: Module to Automatically Create URLs from Article Titles for Drupal 8

texts:
I am wondering if there exists a module that would automatically create "nice" URLs using titles of posts in Drupal 8. I am aware of aliasing; however, if there is a lot of posting activity on the site,  it can become a substantial time sink.

Example: (something along these lines would suffice)

Title of a post:

  How to create neat URLs in Drupal 8

corresponding URL:

  www.example.com/how-to-create-neat-urls-drupal-8


texts: How to theme a node form from my custom module?

texts:
I have a node type with machine name "resource", and I'm trying to theme it in my module "modulename".

I've tried doing this:

function modulename_theme() {
  return array(
    'resource_node_form' => array(
      'render element' => 'form',
      // 'template' => 'resource-node-form',
      // 'path' => drupal_get_path('module', 'modulename'),
    ),
  );
}

//I've tried both functions, getting nothing

function theme_resource_node_form($variables) {
  dsm($variables);
  return 'Testing';
}

function modulename_resource_node_form($variables) {
  dsm($variables);
  return 'Testing';
}

I've cleared cache, nothing happens. I've also tried with templating approach:

function modulename_theme() {
  return array(
    'resource_node_form' => array(
      //'render element' => 'form',
       'template' => 'resource-node-form',
       'path' => drupal_get_path('module', 'modulename'),
    ),
  );
}

And placing resource-node-form.tpl.php in modulename module folder. Cleared cache, nothing happens.

Sure I'm doing something wrong, but I can't figure it out. I've used templates for existing forms from a custom theme, but I'd like to do it this way, this time. Better approach for this project I'm working on, I think.

Thanks for your answers, ask me if you need more info!


texts: Can we access paragraph field in views-view-unformatted.twig?

texts:
Is there a way to access the fields in paragraph in views-view-unformatted.twig.
I want to perform checking on field of paragraph before print the row
something like this

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {% if paragraph_field is not null %}
     <div {{ row.attributes.addClass(row_classes) }}>
        {{ row.content }}
     </div>
  {% endif %}
{% endfor %}


texts: Views 2 - Embed a View inside Empty Text of another View

texts:
I want to embed a View (or a display of a View) inside another display of View when these view has no results. I figure out that I can embed a View inside the 'Empty Text' filed. I must say that I can show some php echo "hello world"; using this 'Empty Text' filed, but when I try to embed a View, I can not embed a another View or display of View.

this is one example that I used, but without results:

$viewName = 'test_view';
$display_id = 'page_1';
print views_embed_view($viewName, $display_id);


texts: How to print the relative url or node id for each referenced node in twig?

texts:
I am using paragraphs to render a number of nodes on a page. The nodes are obtained through an entity reference field called 'field_nodeslist' in my cards paragraph type. The cards are then rendered using a custom view layout.

Here is a snippet of my view layout:

{{ content.top_region|striptags}}

{{ content.middle_region }}

The problem I am having is printing the relative path for each referenced node. I have tried the following twig commands but have not had any success so far:

The following allows me to manually specify the node id in twig however that's not what I am looking for:

Any ideas?

Notes/Thoughts: In my first code snippet, the fields in 'top_region' just contains the nodes title. There was an option to link the field to content however I had to add the '|striptag' filter in twig due to additional markup messing up the style. Is it possible to grab the url path from the node title?


texts: List of images with checkbox (user registration)

texts:
This is what I would like to do:

When a user registers on the website they have to give in if some options like for example if they are politically engaged, professionally engaged, an expert, ... .

I also want a field that contains 3 images. And based on the chosen options of the user I would like to select 1,2 or 3 of them. So the user can contain image 1 & 2 or ... .

So I was thinking of 3 images with 3 checkboxes and cross the checkboxes next to the images (programmatically). But is this a good way to do this? And if yes, how can I implement this?


texts: How to have separate private comments for nodes apart from the general comments?

texts:
I have a specific requirement.
Apart from the general comments which everyone can view or post for my custom node I also require private comments thread which will be shared only by the node created user and selected few.
Using the same comments form will not work as it will be viewed by all.
Any inputs on achieving this?

Thanks.


texts: Migration into multi-value field collection

texts:
I am attempting to use the patch in comment #222 of this issue (https://drupal.org/node/1175082#comment-7625869) to migrate data into a multi-value field collection.

I create an array of the objects in prepareRow() but when the migration completes and I review the nodes, only the first item in the array has populated the field collection and no subsequent items have been added. Am I missing something important?

<?php
class IngredientsMigration extends BasicMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = t('Migrate recipe ingredients from the source database into field collections.');
    $this->dependencies = array('Recipe');

    $query = Database::getConnection('default', 'legacy')
      ->select('recipes', 'r')
      ->fields('r', array('id', 'ingredients'))
        ->condition('r.id', array(2), 'IN');

    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationFieldCollection(
      'field_collection_ingredients',
      array('host_entity_type' => 'node')
    );

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array('type' => 'int',
          'length' => 11,
          'not null' => TRUE,
          'description' => 'Recipe ID',
          'alias' => 'r',
          ),
      ),
      MigrateDestinationFieldCollection::getKeySchema()
    );

    $this->addFieldMapping('host_entity_id', 'id')
      ->sourceMigration('Recipe')
      ->issueNumber(16);
    $this->addFieldMapping('field_ingredient_text', 'ingredients')
      ->description(t('See prepareRow method'))
      ->issueNumber(16);

    $this->addUnmigratedDestinations(array(
      'path',
      )
    );
  }

  public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }

    $ingredients_array = preg_split('/$\R?^/m', $row->ingredients);
    $row->ingredients = array();
    foreach ($ingredients_array as $ingredient) {
      $row->ingredients[] = $ingredient;
    }
    return TRUE;
  }
}


texts:
I'm working on a module that takes a form submission and posts it to a rest api, using the webform validator module's hooks.  I'm trying to debug what's going wrong, and I have the following code, which correctly displays $data and $url but nothing for $result (I'm assuming it's null?).

I'm new to drupal and I wonder what I'm doing wrong, with the http_request that it comes back null, or what else I can do to debug.

      $options = array( data => $data,
                        method => 'POST');
      //verify $data
      $errors['item_2'] = $data;
      $errors['item_3'] = $url

      $result = drupal_http_request($url, $options);

      // display the returned JSON result as a form error
      $errors['item_1'] = json_decode($result);


texts:
I run the website for a small nonprofit, and we're looking at Pantheon.  I've imported my code and DB and gotten things basically working, but I have a question about serving large files.  We're a choir and we have a couple hundred MP3s (recordings of rehearsals, so people can practice) that we need to serve.  It's not high traffic at all - probably only a couple dozen downloads per week - but the files can be as big as 100M each.

A CDN would be overkill - all downloaders are local, not spread around the globe.  And it's really not much traffic.

How should I host them?  Just check them in to Git?  They're not currently in sites/default/files, but I could put them there and use symlinks from their current location if that would help.


texts: hook_form_FORM_ID_alter in theme file to toggle field visibility

texts:
I have a boolean check box that I want to control the visibility of an entity-reference field below it.  By default, this check box is unchecked, which means the entity-reference field should not be shown.

I've tried a handful of things in my .theme file, but I can't seem to solve the problem.

use Drupal\Core\Form\FormStateInterface;

function mytheme_form_node_news_form_alter(&$form, FormStateInterface
  &$form_state, $form_id) {
    $form['field_news_top_story_image']['#states'] = [
    'visible' => [
        ':input[name="field_news_topstory"]' => ['checked' => TRUE]
    ]
];

}

node_news_form (and eventually node_news_edit_form once I figure this out) appears to be the form I want to affect.  field_news_topstory is my checkbox and field_news_top_story_image is the entity-reference field I want to hide* until field_news_topstory is checked.  *I've set this field to disabled in Manage Form Display.

Am I close?  :)

EDIT: Had my code backwards, but still not working.


texts: Can you temporary grant a user permission to avoid captchas in drupal 7?

texts:
I have a module which alters a webform's form. Depending on the user agent, I want to grant the current user the permission to skip captchas, so that the captcha block wont appear at the end of my webform. The problem is, within the init function of my module, if I enable the following line:

if (functionWhichChecksStuff()) {
        user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('skip CAPTCHA'));
    }

the permission is being granted for ALL anons, every time since it actually grants the permission to that user role permanently.

Is there a way or function which does that dynamically and temporary?


texts:
I am trying to convert this from D7 to D8:

l(drupal_strtoupper($field),
sprintf('http://finance.google.com/finance?q=%s',
$exchange . ':' . $field),
array('attributes' =>
array('target' => '_blank',
       'title' => (drupal_strlen($title)) ? $title : $field)
)
);

I am doing this and it produced error:

return Link::fromTextAndUrl(Unicode::strtoupper($field), Url::fromUri(sprintf('http://finance.google.com/finance?q=%s'),$exchange . ':' . $field))->toString();

  InvalidArgumentException: The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core/lib/Drupal/Core/Url.php)


texts:
I tried creating a view where I display user's unpublished nodes.
The view works flawlessly for super user 1, but it doesn't work for authenticated users where no nodes are displayed though the authenticated user can directly access the unpublished node and edit it.
Things I tried:
1. Try different display formats (e.g. fields, full content)
2. Removed all kinds of filters
3. Removed all kinds of access rules for the view
4. Reviewed permissions:
  a. Administer content is unchecked for authenticated user
  b. View own unpublished content is checked for authenticated user
  c. create/edit/delete content permissions are set for authenticated user
  d. Bypass content access control unchecked for authenticated user

Is this normal or this is a views' bug?

UPDATE:
I posted my question on Drupal bug tracker. It seems that a module is causing the issue. https://www.drupal.org/node/2810077
I tried creating a new Drupal 8 installation with a view that shows unpublished content and now it displays all unpublished content regardless of user's permission...


texts:
I have imceimage.module,v 1.1.2.4. the default of this module is to create a table for the field i want to create as below:

desc content_field_slideshow_image;
+-----------------------------------------+------------------+------+-----+---------+-------+
| Field                                   | Type             | Null | Key | Default | Extra |
+-----------------------------------------+------------------+------+-----+---------+-------+
| vid                                     | int(10) unsigned | NO   | PRI | 0       |       |
| nid                                     | int(10) unsigned | NO   | MUL | 0       |       |
| delta                                   | int(10) unsigned | NO   | PRI | 0       |       |
| field_slideshow_image_imceimage_path    | char(255)        | YES  |     |         |       |
| field_slideshow_image_imceimage_width   | int(11)          | NO   |     | 0       |       |
| field_slideshow_image_imceimage_height  | int(11)          | NO   |     | 0       |       |
| field_slideshow_image_imceimage_alt     | text             | YES  |     | NULL    |       |

and i want to add new field for seo_alt

| field_slideshow_image_imceimage_seo_alt | varchar(255)     | YES  |     | NULL    |       |

I have doen this:
1- i have altered the table  alter table content_field_slideshow_image add  field_slideshow_image_imceimage_seo_alt varchar(255);
2- added 'imceimage_seo_alt' => array('type' => 'varchar', 'length' => 255)); in imceimage_field_settings hook
3-changed #columns in imceimage_elements hook to be  '#columns' => array('imceimage_path','imceimage_width','imceimage_height','imceimage_alt','imceimage_seo_alt'),
4- added $element['#value']['imceimage_seo_alt'],  to $element['imce_view'] in imceimage_process hook
but now when i edit a slideshow and add the imceimage_seo_alt, it wouldn't be saved in the database :(... what shall i do to add this customized field??
Thanks for your help


texts: Host doesn't support nested folder structures for deployment. How do I adjust Composer?

texts:
So, I have to deploy a drupal 8 site to a host which doesn't provide functionality to specify an entry point for a Drupal site which is nested below the site root folder. How can I update the folder structure to have everything in the server's site root?
What I tried initially was to move the contents of the site_root/web/ folder up to the site root, but this causes 500 errors. I'm not sure since I can't see the errors on the host server, but replicating the scenario on my dev machine points to the autoloader.php file looking in the wrong place PHP Fatal error:  require(): Failed opening required '/var/www/html/ab-test/../vendor/autoload.php'.

I have tried to resolve this by first following the suggestion to re-run composer install from the site root but that doesn't seem to help. When I manually update where the autoloader.php should be looking, I then get this errorPHP Warning:  require(/var/www/html/ab-test/vendor/composer/../../load.environment.php) which again suggests that the file/folder structure is being set somewhere I'm not thinking of or don't have enough experience to check.
So, my convoluted question comes down to how do I switch from a nested to a non-nested folder structure without everything freaking out?


texts: How to selectively import and export content between 2 Drupal websites?

texts:
How to merge simple core content into from site a to site b. Content is created using core functionality and modules.

Let's say I have 2 Drupal 7 sites, both have same configuration and modules.

Site A has:

3 content types
3 taxonomies
3 articles

Site B has:

1 content types
1 taxonomies
1 articles

How do I append content of site B to site A?

I want the content from site A to be appended to site B. If I do backup migrate, the content of site A will be overwritten.

I've noticed that backup migrate can have manual selection of what to export, but it will overwrite destination right?

What is the best procedure for this?


texts:
I am developing a custom module in Drupal 8. My custom module include many JavaScript and CSS files which make the site really slow and I don't want them in all pages. I have developed some custom blocks and each JavaScript and CSS library correspond to a block. I want those files on those pages of the site where my custom blocks are visible.

In my last Drupal 8 project, I have done something like the following.

function HOOK_page_attachments(array &$attachments) {
    $user = \Drupal::currentUser()->getRoles();

    if(in_array("administrator", $user)){
        $attachments['#attached']['library'][] = 'module/library';
    }
}

I am not sure how to check which blocks are visible in the page.


texts: How to export custom module form content as PDF file in drupal 7?

texts:
I have a custom module with some form fields. I want to submit this form and generate pdf file of user filled values in new tab. I am trying with TCPDF but it doesn't display any fieldset ( as border ).

In submit funciton , I am taking $form array and using drupal_render($form) that render form values as html ( if I print ). If I pass this html to WriteHTML($html, true) , it gives pdf but there is no styling left on that form.


texts: How to block a content type from the RSS feed

texts: I simply want to remove one of my content types from being displayed in the feed, I can't find a solution anywhere - I would have thought there would be an option under Content Types which says "Don't put in feed" lol


texts: Render image or entity in a custom block!

texts:
I want to render product content type in a custom block with a custom view mode. I have a field product_teaser in my article content type that reference the product that is I want to render in the custom block using advert view mode

The content type to be rendered: "product"

The view mode to be rendered with: "advert"

The product teaser only contains an image and a buy=now button I can easily place using twig. So placing only the image in the render of the custom block should be enough for this to work But I have been trying to render the image for a while and I could not do it.

This is my first approach to do this, Rendering the whole product advert.

  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $view_mode = 'advert';
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
      $pre_render = $view_builder->view($product, $view_mode);
      $render_output = render($pre_render);
      return $render_output;
    }
    return [];
  }

Render output is an empty string for some reason. $pre_render has got view mode and node array having all the product fields, everything looks good except that render($pre_render) return an empty spaces string.
This is the error being output from this approach "Argument 1 passed to Drupal\Core\Render\Element::isEmpty() must be of the type array, object given"

My second approach was to get the image URI of the product advert and render it manually

$build= array();
    //Gets current node to check for which product to be displayed.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $product_id = $node->get('field_product_teaser')->getValue()[0]['target_id'];
      $product = \Drupal::entityTypeManager()->getStorage('node')->load($product_id);
      $product_advert_url = $product->field_teaser->entity->url();
    }

    $build['image'] = [
      '#theme' => 'image_style',
      '#style_name' => 'thumbnail',
      '#uri' => $product_advert_url
    ];

    return $build;

This is the error being output from this approach "Class name must be a valid object or a string in Drupal\image\Entity\ImageStyle->buildUri()"

How to fix these errors ??, I prefer the first method because it will be easier if I needed to add anything to the product teaser later.


texts: How to associate an entity view mode with a path? (Commerce product entity)

texts:
I created a view mode for a Commerce product entity with http://drupal.org/project/entity_view_mode , now I would like to associate this with a path like myproduct/[entity_id] , so I can attach meta tags and everything else to it.

How would I go about this? Essentially, I am trying to avoid using a product display node for a product entity.


texts: Views view unformatted and outputting taxonomy custom field

texts:
Original problem I had was I setup a taxonomy called Category.  I added some vocabulary to my Category taxonomy. Some of the terms I added have contain spaces.  The labels should have spaces so I want to keep them there. I want to remove the spaces from the Category name when they are output in the views view unformatted templated.

This would solve all of my problems if I can get those spaces out of the category names.  I setup a custom field on the taxonomy terms to handle this, but I don't know how to access the custom fields of the taxonomy term from the views-view-unformatted.html.twig template.  Is there a preprocesser function that can do this?  Something where I can convert the category and just remove the spaces or change the value output from label to field_nospace_category ?

More experimenting

I setup a view of type page to display the articles in my content type Articles.  I'm using using the unformatted list and I created a custom template called views-view-unformatted--my_view_id.html.twig.  I see that this is the template that is outputting on my page.

I'm trying to output the taxonomy terms custom field as a class on the div that has {{ row.attributes.addClass(row_classes) }}

The div should end up looking like this:

...

I've tried several variations to try to get to the values. Inside of the for row in rows loop, i put:

{{ node.category.entity.field_category.value }}
{{ row.content['#node'].field_category.getValue().0.target_id }}
{{field_category}}
{{row.content['#elements'].field_category.getValue().0.target_id}}

I have tried to debug using Kint, Dump but my install keeps either throwing errors (out of memory) or blank white page.

Please help. Thank you in advance.


texts: How do I load classes using the ctools plugin class loader?

texts: Perhaps, the question should be how do I implement ctools plugins using classes to extend different types of an object? I can't find a simple explanation.


texts: Display HTML code in a Drupal field as plain text

texts:
I am using Drupal as a blog for posts about programming. Naturally, I have to post code samples.

When I post the code samples, Drupal renders them as actual HTML. How can I stop this from happening?

Example,

Thank You

^ This gets displayed as the words "Thank You" with the listed formatting in the inline style.

^ This doesn't get displayed at all.

Steps I have taken

I have created a new input format and turned off all the filters.
I wrap the code in both  and
 tags.

I know Drupal has a filter called " Display any HTML as plain text". If I use this, then it works. But then all my formatting for the test of the post (e.g. paragraphs, links) get displayed as text making the post unreadable.


texts: How to avoid the error 'array expected string given' in db_query

texts:
I am getting this error: Argument 2 passed to db_query() must be an array,
string given. In db_query in below function.

function uc_guest_checkout_uc_checkout_complete($order, $account) {
  if (!empty($_SESSION['uc_guest_checkout'])  && !user_is_logged_in()) {
    switch ($order->data['complete_sale']) {
      case 'new_user':
        // For guest checkout, we replace the ubercart generated username and email
        // for a new user with one that is more anonymous.
        $name = uniqid('anon-', TRUE);
        $mail = $name . '.' . uc_store_email();
        db_query('UPDATE {users} SET name = "%s", mail = "%s" WHERE uid = %d', $name, $mail, $account->uid);
   break;
  case 'logged_in':
    // If the order is marked logged in but anonymous, this means that
    // we must have set the uid to the default account, but still treat
    // this as a new user.
    $order->data['complete_sale'] = 'new_user';
    break;
    }
  }
  _uc_guest_checkout_end();
}

I tried this queries but none were creating account with valid names and emails as per db_query which is throwing error but successfully creating user accounts.where as these below queries creating names with random names.

db_update('users')
        ->fields(array(
            'name' => $name,
            'mail' => $mail
        ))
        ->condition('uid', $account->uid)
        ->execute();

db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
                array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

How do I resolve this?


texts:
I have a problem with my header cart which is a block showing how many product have been added to the cart.

In the default language the order proces works just fine.
However when I test the proces in another language there is a problem with the link of the header cart.

The link refers to the default language shopping cart form instead of the language the current page is.

When I manually add in the url the specific language (e.g. de/cart) it works just fine including the rest of the order process.

Does anyone know what the problem would be?


texts: Multistep ajax form, rebuild form and replace contents with the current step

texts:
I have a multistep form.
In the first step i have an AJAX submit callback that updates my &$step in $form_state and should return the next step of the form in the same page (replace contents of the form with the form elements in the second step) e.g.

  <?php

  funtion my_form_builder($form, &$form_state) {
     if (empty($form_state['step'])) {
      $form_state['step'] = 'step_1';
     }
     $step = & $form_state['step'];
     // build step 1
     if ($step == 'step_1') {
       $form['first_submit'] = array(
         '#type' => 'submit',
         '#ajax' => array(
           'callback' => 'form_first_submit',
          ),
         '#executes_submit_callback' => TRUE,
       );
     }
     // build step 2
     if ($step == 'step_2') {
       $form['elem_2'] = array(...)
       $form['elem_2_1'] = array(...)
     }
     return $form;
  }

  function form_first_submit($form, &$form_state) {
     $current_step = & $form_state['step'];
     // store values...
     // move on to the next step
     $current_step = 'step_2';

  $form = drupal_rebuild_form('my_form_builder', $form_state, $form);
  $commands[] = ajax_command_replace('#main-content', render($content));
  // return  ajax
  return array(
   '#type' => 'ajax',
   '#commands' => $commands,
  );
  }

So, naturally after the first submit, i should be able to rebuild my form and return to the #main-content the form elements defined for step 2.
Why this doesn't work?I see the code passes on the right places and rebuilds and prepares the form for rendering.

I tried with drupal_build, drupal_retrieve_form and im getting nowhere.

If i drupal_get_form('another_form_id') it will work as expected.

Where is my error?


texts: How to display a page of a taxonomy term differently from the default view?

texts:
I activated the "Taxonomy term" view to customize the time display. I want to display some terms from another differently. How to do this ?

I have cloned my view "Taxonomy term" and applied to it a criterion of filtering by type of content displaying only my "sujet". Then I customized its display.

The problem, when the cloned view is enabled, all terms show a blank page.


texts: How do I add JavaScript specific for a view?

texts:
I have a view in my site that has a specific class name. I want to know, inside the template.php file of a theme, how I can know if a view with specific class name is available in the requested page.

This is very important for me because I need to include specific JavaScript and CSS, when a view with a specific class name (such as image-gallery) is used in a page.


texts: Set (add) group role using Rules when organic group membership is updated?

texts:
Using Rules, I am trying to set a users group role anytime a new membership entity is updated, however it appears roles are not brought into scope for me to set data value nor "grant og role"

All I want is

Event: After updating an existing og membership

Action: Grant OG role: Licensee (or set data value role: Licensee or whatever og centric things it asks for)


texts: $form_state does not follow same array structure as $form

texts:
I built a form in a form plugin like so.

public function buildForm(array $form, FormStateInterface $form_state) {
$array[0] = 'value1';
$array[1] = 'value2';
$array[2] = 'value3';
$array[3] = 'value4';

$form['field_1'] = [
    '#type' => 'value',
    '#value' => 'test value',
];

foreach($array as $item){
    $form['fields'][$item] = [
        '#type' => 'textarea',
        '#title' => $item,
    ];
}
    $form['actions'] = [
        '#type' => 'actions',
    ];

    $form['actions']['submit'] = [
        '#type'  => 'submit',
        '#value' => t('Submit'),
    ];

    return $form;
}

The form is built just fine and I can return the values upon submit like so,

public function submitForm(array&$form, FormStateInterface $form_state) {
    die(print_r($form_state->getValues()));
}

This is part of the output I receive

[field_1] => test value
[value1] => User input for value 1 text area
[value2] => User input for value 2 text area
[value3] => User input for value 3 text area
[value4] => User input for value 4 text area
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

The issue is, I want value1,value2,value3, and value4 to appear as children in the ['fields'] part of the array.

To demonstrate, I'd want the output to appear like so.

[field_1] => test value
[fields] => [
    [value1] => User input for value 1 text area
    [value2] => User input for value 2 text area
    [value3] => User input for value 3 text area
    [value4] => User input for value 4 text area
]
[submit] => Drupal\Core\StringTranslation\TranslatableMarkup Object

The ultimate goal is to be able to use a foreach loop on the fields array, like this

foreach($fields as $key => $value){
    print_r('This is the key: '.$key.' and this is the value: '.$value);
}

I also attempted declaring 'fields' as a container first like so

$form['fields'] = [
    '#type' => 'container',
];

but it has no effect. How would I group form elements into an array when parsing the form state?


texts: sharing authentication within two drupal distributions

texts:
I am looking for a module or a way where two different drupal distributions can share the same authentication or user database ? Is there a module that can help with that ?

possibilities-

if user A logged into site-1,  the user should be logged in automatically to site-2.

if thats not possible, if user 1 creates a login on site-1, he should also be able to use the same login credentials on site-2 or vice versa.


texts: Machine readable coordinates to Geofield

texts:
I got a long txt file full of cordinates. Like this for every line;

 {"RT**n":"*****","RT**o":"*******","WGS**_lat":"******","WGS**_lon":"******" }

There are numbers, I just hide them since this is just a example.
Anyway. I got a lot of these and it would take me forever to manually insert them. Is there any way to import these into D7 Leaflet Geofield?

Thanks


texts: How to delete 1600 users and 2500 posts?

texts:
A couple years ago I configured a site with Drupal 6.9, and then I forgot about it. I have 160 pages of users that are all spammers and I need to delete all but 3. Doing this one page at a time is painfully slow due to the MySQL calls (I guess). I also have about 2500 forum posts to delete.

I'm a little afraid to delete records from the database directly.

I saw a module called "mass delete", but it is for Drupal version 5 and not available for version 6.


texts: Ubercart: PHP message if a Product is in cart

texts:
I need help with a boolean function in PHP. It's simple (but I'm not PHP savvy enough to do it myself). I just need to create a block with a message (not a system message because I am using better messages and I don't want people to close the pop-out without even reading it) that will only show in the ubercart cart
page, if two of the products are in the cart. Else it won't show.

Of course, if there is a better workaround tio this, I am open to suggestions.

Thanks in advance to whomever might wanna help.