texts: Create a general rewrite rule in .htaccess

texts:
In an upgrade scenario I have to provide some alias URLs like www.server.com/reading_23.html that should actually deliver www.server.com/reading/23.

I spent lots of hours trying to make that work by adding a line in .htaccess:

RewriteRule reading_(.*).html reading/$1

I have put that line into the standard D8 .htaccess, right after RewriteBase /. Unfortunately none of my attempts worked. The /reading is a path that's provided by one of my modules.routing.yml.

EDIT, 18.1.
This seems to be very special for Drupal because it just doesn't work with the existing D8 redirects. I can only make a redirection ([L,R]) work but I don't want my end-users to see the reading/23 path in their browser.
So actually the question is how to make URLs like reading_23.html possible with Drupal, the routing parameters can only live as separate parts of the path (like reading/{number} is ok but reading_{number}.html is bad).

Anyone who knows how to do this?

I do not want to create aliases in my Drupal DB for all node-Ids.

[EDIT Nr 2. 18.Jan 2017]

The Solution is an inbound Path Processor like 4k4 wrote. Thanks a lot.

[END EDIT]


texts: Drush sql-sync not placing file in specified dump-dir

texts:
I have a dev and staging alias setup for drush and they are both working correctly. I included a reference to where I want the dump file placed during a drush sql-sync using

  'path-aliases' => array(
    '%dump-dir' => '/home/.drush/db_dumps'
  )

However, when I run the command it runs successfully but it doesn't use my dump directory. Instead it uses /home/user/drush-backups. I tried changing the location of my dump-dir to a location inside of the drupal site folder, but it still doesn't work.

One of the solutions that I found was to include the --source-dump option (which points to the same location as I have in %dump-dir) when running drush sql-sync. It seems like if that's the case, then why even bother adding it in my alias file.

Another solution states to also include a reference to the actual dump file using %dumpin the path-aliases array. I tried that and it still doesn't work.

Is there a solution to this or is it not suppose to work at all?? Because the example.aliases.drushrc.php file doesn't mention dump-dir at all.

Using:
Ubuntu 14.0.4,
Drush 8.0.5,
Drupal 8 site

Thanx


texts: How to output variables from a multi-value field into html on a node tpl overrride

texts:
I have overridden my node tpl page and want to output variables from a field into html. The field is called: "Features Ticked"

I understand that this php code will output the information:

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

I see the variables are all visible with css tags around them.

Is this the only way I can outpout this information as I want to strip the html tags, how do I do that?

I want to just output row by row then use html within the tpl file.

At the moment I get all these classes:

Features/Ticked:&nbsp;

Text 1

Text 2

Text 3

What I want to do it output just:

Text 1
Text 2
Text 3

Then wrap my own html around it.. I think I can override the field.tpl.php file to remove the classes, but I don't know how to output each line of text using php in 3 separate lines of code.

I thought i was something like:

<?php print render($content['field_features_ticked'][1]) ?>
<?php print render($content['field_features_ticked'][2]) ?>
<?php print render($content['field_features_ticked'][3]) ?>

But my knowledge of php kind of end there!


texts: How can I display information about a referenced node within a content creation page?

texts:
I have a content/entity type called venue. On these venue nodes, there is a link to review the venue. When users click on this link, they are taken to a content creation page for a review content type. The content creation form has an entity reference field, populated automatically with Entityreference Prepopulate, so that the review is associated with the correct venue.

I would like to display information about the venue being reviewed (including name, address, etc.) on the review content creation form, for the purposes of clarification for the user. I'm assuming that there is some way to fetch this information since both the url (/node/add/review?field_venue_reference_review=9) and the reference field contain the NID for the venue.

What would be the best way to pull information from the venue node and display it in/above/near the review form? I've tried to do it using a views block with a contextual filter, but it seems that since the NID neither has its own place in the url, or is in the standard place that an NID would be placed on the url of a node page, views cannot detect it. There may be another way to do this that I'm not realizing.

Any help would be greatly appreciated, as I've being searching for an answer for quite some time. Thanks in advance for any help.


texts: How to redirect to l() function link after login?

texts:
I'm having a Simplenews newsletter template with a link guiding newsletter readers to a intranet site with more news.

<?php print l('hier.', 'node/' . $build['#node']->nid, array('absolute' => TRUE)); ?>

My problem now is, that if the user is not logged in, that link only brings him to the login site, where he is then stucked.

What would I have to do or what function would help me to somehow provide a link that redirects the not logged in user to the proper aim after logging in, and which would not affect the already logged in user?


texts:
I have two content types: Region and City. Region nodes include City nodes; every City node is related to some Region node.

How I can create a relationship for this situation? When I create a Region node and refer a City node in a field, all City nodes have its Region referencing field set to this Region node and vice versa.


texts: Event Calendar Event not displaying to user

texts:
I have created event calendar as guided here http://drupal.org/node/1250714. Now Event with date is displaying correctly for admin users but it's not showing for authenticated and anonymous users. I have checked and there is no permission for event date.  Also, I have given all modules permission to both type of user.  Still not working.
Any Suggestions?


texts: What is the difference between the classes ArchiverTar and Archive_Tar?  Which one is a Drupal module supposed to use?


texts:
function module_form_alter(&$form, $form_state, $form_id)  {
  if (substr($form_id, 0, 28) == 'uc_product_add_to_cart_form_') {
    $form['qty']["#title"] =t('Adults');
  }

  if ($form_id == 'webform_client_form_210') {
    try {
      if (isset($_GET['pid']) && isset($_GET['attributes'])) {
        $nid = $_GET['pid'];
        $attributes = $_GET['attributes'];

        $node = node_load($nid);
        $type = node_type_get_name($node);
        $form['submitted']['produit']['#default_value'] = $type.' '.$node->title;

        $details_product='';
        foreach ($attributes as $aid => $oid) {

            $attribute = uc_attribute_load($aid,$nid,'product');
            $option = uc_attribute_option_load($oid);
            $product_option = $attribute->label.' : '.$option->name.' | '.$option->price;
            $details_product = $details_product.PHP_EOL .$product_option;

        }
        $form['submitted']['details']['#default_value'] = $details_product;
      }
    } catch (Exception $ex) {}
  }
}

Above is my hook_form_alter implementation. All I wanted to do is, to generate all options of the product chosen by user, but I want to have the price displayed and calculated like the amount and subtotal like in Ubercart module.


texts: Correct way to call a service in a controller

texts:
I'm new to services (and drupal 8!) and trying to figure out services. I think perhaps I'm just doing the create in an outdated way. What I want do is make my 'hello generator' a service and call it in another controller with the following:

DBController.php

namespace Drupal\db\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\db\DbServices\HelloGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;

class DBController extends ControllerBase
{
private $helloGenerator;

public function __construct(HelloGenerator $x) {
    $this->helloGenerator = $x;
}
public function say($count) {
    $hello = $this->helloGenerator->getHello($count);

    return new Response($hello);
}

public static function create(ContainerInterface $container) {
    $x = $container->get('db.hello_generator');
    return new static ($x);
}
}

HellGenerator.php

namespace Drupal\db\DbServices;

class HelloGenerator {

public function getHello($count) {
    $foo = 4 + 4 + 4;
    return $foo . ' ' . $count;
}

}

db.services.yml

services:
  db.hello_generator:
     class: Drupal\db\DbServices\HelloGenerator

db.db_says:
  path: /db/says/{count}
  defaults:
    _controller: '\Drupal\db\Controller\DBController::say'
  requirements:
    _permission: 'access content'


texts: Can't choose a Taxonomy term as a Context condition

texts:
I'm trying to create a context based on taxonomy. When I use the Context UI, the Taxonomy form is not populated with my taxonomy terms. Here's a screenshot of my empty taxonomy selector.

I have three terms in one vocabulary, and all terms have at least one node associated with them.

What's going on?


texts: How to add custom css and javascript file in Drupal 8.


texts: Change Sent By in Drupal 6 Webform Module?

texts: Is there a way to make it appear the email is coming from the person who submitted it, instead of the site it resides on? The webform has an email field, and I'd like to use that as the source of the email.


texts: Show a node through a view in the node panel layout

texts:
In Drupal 7, I use the node template panel layout to display any node/contents.
is there is a way that I can show a node through a view in the node panel layout for the particular node?

i.e : I am having 10 contents displaying on my home page belonging to "vehicle" content type.,
once I click on a content it should take me to the particular page listing all the details about it through a view.

I guess I need to pass some arguments here when creating the view/panels, but not sure where exactly i should do that..

Thank you


texts: How to enable Text formats after disabling it in Drupal?

texts:
In attempting to get pictures inline with text, I did the following:

Configuration>> content authoring >> text formats>> and disabled Full HTML and Filtered HTML formats.

This clearly did not give me the desired result as now all text is no longer visible on my Drupal website.

How do I re-enable this text on the website?


texts: how to add parameters to html email template

texts:
I have a working html email using modules: Mail System, HTML Mail, SMTP Authentication Support.

And I want to include some parameters/variables in the html email template file:

htmlmail--htmlmail.tpl.php

some variables include: $base_path etc. from page.tpl.php variables

From what I've read from the Internet, you may use "hooking" and I haven't yet hooked variables so far for my template file.


texts: What is the "correct" way to determine how many forum post/comments happened in a month

texts: I have a drupal advacned forum where I need to track the number of posts.  I was using the node number but now believe this is wrong.  What is the preferred/correct way to count the posts (both new topics and comments) in a given month?


texts:
I have sidebar block which has id "block-block-11--2". After including this statement in the node template

";
 $search_block  = module_invoke("views","block_view","-exp-category_wise_search-page");
 print render($search_block['content']);

all css of tat id is messed up, because id of that block has been changed to block-block-11. If I comment that code in node template the previous block id comes properly and all css works fine with that.Those two are entirely different blocks.

NOTE I am not trying to place same blocks at two place.

What is the issue over here? Thanks in advance.


texts: Set a Document File in a webform submission programmatically

texts:
I have writen a PHP class that saves a pdf file programmatically. The class contains a function that returns the Drupal path private://documentA.pdf

I would like to attach the file to a webform submission:

$webform_submission = \Drupal\webform\Entity\WebformSubmission::load(ID);
$data = $webform_submission->getData();
$data['file_attachment'] = //retrieve the file
$webform_submission->setData($data);
$webform_submission->save();

Webform element type of file_attachment is Document file.


texts: How do I import a library from Github when the module is installed

texts:
I want to add https://github.com/googleads/googleads-php-lib library to my module Drupal 8 I try to add composer. json in the folder module but is not load when I installed module this is solution to upload this library without command "composer update "?

this is my composer.json

{
  "name": "drupal/googleads-php-lib",
  "description": "Integrates the googleads-php-lib library into Drupal",
  "type": "drupal-module",
  "require": {
    "googleads/googleads-php-lib": "25.0.0"
  }
}


texts: How to display the input box next to the label in a form?

texts:
My objective is to improve the look and feel of a form developed in Drupal 7.

By default, I have (as an example):

Name (label)
BLANK INPUT box (below the label)

How to display the label and input box as inline ?


texts: After deleting all nodes, how do I reset the node ID to start from 1 again?

texts:
I generated tons of dummy content for testing, and then deleted them all.
As nid is auto-increment, newly created node will have a nid of last created nid +1.

How can I make nid start from 1 again?


texts: Display only the value of a field in a content-type template

texts:
I'm attempting to display a plain text field so that I can use it to embed youtube videos

In my template I have

However when it renders it produces a mess

<iframe width="420" height="315" src="https://www.youtube.com/embed/&#10;&#10;&lt;!-- THEME DEBUG --&gt;&#10;&lt;!-- THEME HOOK: 'field' --&gt;&#10;&lt;!-- FILE NAME SUGGESTIONS:&#10;   * field--node--field-video--beer.html.twig&#10;   * field--node--field-video.html.twig&#10;   * field--node--beer.html.twig&#10;   * field--field-video.html.twig&#10;   * field--string.html.twig&#10;   x field.html.twig&#10;--&gt;&#10;&lt;!-- BEGIN OUTPUT from 'core/themes/stable/templates/field/field.html.twig' --&gt;&#10;&#10;            &lt;div data-quickedit-field-id=" node="" 15="" field_video="" en="" full"="">C0DPdy98e4c&lt;/div&gt;

&lt;!-- END OUTPUT from 'core/themes/stable/templates/field/field.html.twig' --&gt;

" frameborder="0" allowfullscreen&gt;

I understand that part of it is because I'm in debug mode, but it's also wrapping it in a quick edit field div. And even if it didn't I'd rather not exit debug mode just to work on this. Is there a way to output just the value and nothing more?
Like something similar to {{ content.field_video.value }}?

If I can't disable quick edit field by field, is there a way to print a field while keeping the HTML intact? When I put the entire iframe into field it turns the html tags into text.

I tried

{{ content.field_video|raw }}

but the output still showed the html tags as text. I tried

{{ content.field_video.value|raw }}

But that did not show anything.


texts: How to show the contents of view page from template?

texts:
I'm trying to theme a view page on Drupal 7, I used views-view--name-of-page.tpl.php

So now it's blank right? I invoked some blocks on the view page and added some divs to style but I can't seem to show the contents of the view page.

I have tried

print render ($content);
print $content;
print $page;

etc.

Like what we do for node. but it's not working on views template.

Can anyone suggest me?


texts:
I have a a view with Taxonomy terms on the front page.I want when I click on a taxonomy term,this taxonomy term to be passed to a second view as an argument to an exposed filter.The second view is on another page.How can I accomplish that?Is there any module for this?
Thanks in advance

SOLUTION
I finally found a solution.I have rewritten the ouput of the taxonomy term to something like that second_view/[tid] .So when I click on a taxonomy term I am redirected to the second view which is filtered by the tid.That's it!


texts:
I have StreamWrapper for Amazon S3 and I have noticed chmod is not working. I have looked into the \Drupal\Core\File\FileSystemInterface::chmod and it clearly states that contrib modules should provide their own handling since PHP's chmod does not support streams. I have looked at services and it looks like the file_system service is not a plugin manager and it does not have service tags.

So how can I provide my own FileSystem for my stream?


texts:
I would like to know if it is possible to capture payments by subscribing to order transition events.

Example:

Transaction mode: Authorize only
On order placed - Capture some amount (application fee)
On order validated - Capture outstanding amount

Thank you!


texts: What operation should I use to write node's information in an email when the node is saved?

texts:
I am using hook_nodeapi() to display the node's information in an email when the user clicks on the "Save" button. I tried writing code for the "presave" operation, but that didn't work the way I wanted. I tried using a query to pull out the node data, but the data wasn't in the database until after the "postsave" operation.

Which $op is the right one for me? I tried 'insert' as well, and that didn't work.


texts: How Do I Complete a commerce order checkout Programatically?

texts: I want to Complete a commerce order checkout Programmatically after the transaction has been completed  so far I, have done this creating a commerce order programmatically and saving it. Now, I want to complete the checkout process programmatically I am calling commerce_checkout_complete($order_id); but it sets the page in exit mode.


texts: image share issue for single variant product

texts:
I am using Service Link module. On product display page, one of the product variant is displayed. The products having more than 1 variant, sharing proper image [shows meta property="og:image" content="..." in view source ].
But single variant product is not producing og meta tag.

I am using token [node:field-product:1:field_images] in Images input field of 'Open Graph' meta tags.


texts: Order product ID field returns "0" in Views

texts:
I have a View of type "Orders" for my Ubercart orders. I am trying to display the "Order Product ID" field value for each order product so that I can count those as distinct. I added the relationship "Order: Products", which makes the "Order Product ID" field available; however, that field is returning a value of "0" instead of the actual Order Product ID displayed in the database. How can I resolve this?

Here is an export of my view:

$view = new view();
$view->name = 'order_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'uc_orders';
$view->human_name = 'Order Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Order: Products */
$handler->display->display_options['relationships']['products']['id'] = 'products';
$handler->display->display_options['relationships']['products']['table'] = 'uc_orders';
$handler->display->display_options['relationships']['products']['field'] = 'products';
/* Field: Order: Order ID */
$handler->display->display_options['fields']['order_id']['id'] = 'order_id';
$handler->display->display_options['fields']['order_id']['table'] = 'uc_orders';
$handler->display->display_options['fields']['order_id']['field'] = 'order_id';
/* Field: Ordered product: Order product ID */
$handler->display->display_options['fields']['order_product_id']['id'] = 'order_product_id';
$handler->display->display_options['fields']['order_product_id']['table'] = 'uc_order_products';
$handler->display->display_options['fields']['order_product_id']['field'] = 'order_product_id';
$handler->display->display_options['fields']['order_product_id']['relationship'] = 'products';
$handler->display->display_options['fields']['order_product_id']['link_to_entity'] = 0;

Thanks!


texts: How to retrieve ConfigEntity instance from config factory?

texts:
I have defined a config entity in my module (schema and class that extends ConfigEntityBase) - MyConfigEntity.

When I use config factory to get config, Drupal returns instance of Config or ImmutableConfig. How can I retrieve instance of MyConfigEntity instead?

$config = \Drupal::config('my_module.config.something');
// Now $config is instance of ImmutableConfig.


texts: How do I mark translation strings as non-customized?

texts:
Drupal 8 distinguishes between "customized" and "non-customized" translations.

A customized translation is a translation that has been imported from a module and then changed at /admin/config/regional/translate.

So, if I edit a translation that has been imported, it becomes customized.

What if I edited many translations, but then changed my mind and wanted to restore them to the default?

How can I revert a customized string into the original non-customized one?  (And is it possible to do this to strings in batches?)


texts: add a line item with custom fields to an order programatically

texts:
On drupal7, I use commerce webform module to allow users to add products by checking checkboxes. What i want to do is to add a custom product (its price is O$) to put on it custom fields whose values are submitted by the commerce webform. It's a way to add informations on the order and to have it displayed on the line items in the cart. So i create a custom module with a hook_form_alter. In my webform, i have three components:
- A productfields (with a list of available products): the user can do a multiple selection (to select several products of the same type)
- A field called imagethumb (a image field)
- A field called infobulle (a text field)
What i want to do is to get the values of the two fields (that is simple), and add them to the new line item, so they can be displayed in the cart.
Here is my code:

/**
* Implementation of hook_form_alter().
*/
function custom_webform_form_alter(&$form, &$form_state, $form_id) {
  // Add validation for a particular Webform node:
  if ($form_id == 'webform_client_form_15') {

// Add the submit handler after the existing Webform submit handler,
// but before the second Webform handler. Pop off the first one and add
// ours second.
$first = array_shift($form['#submit']);
array_unshift($form['#submit'], $first, 'custom_webform_submit_15');
  }
}
/**
* Submit handler for Webform ID #15.
*/
function custom_webform_submit_15(&$form, &$form_state) {
  global $user;
  $uid = $user->uid;
  $product_id = 7;

  //load the order
  $order = commerce_cart_order_load($uid);

  //load the product
  $product = commerce_product_load($product_id);// On charge le produit

  // Create a line item with quantity 1 and this product.
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

  //get the form values that we need

  $nid = $form_state['values']['details']['nid'];
  $sid = $form_state['values']['details']['sid'];
  $imagethumb = $form_state['values']['submitted_tree']['image_thumb'];
  $infobulle = $form_state['values']['submitted_tree']['info_bulle'];

  //create a wrapper
  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item, $info);

  //and here is the problem
  $line_item_wrapper->commerce_webform_nid = $nid;
  $line_item_wrapper->commerce_webform_sid = $sid;
  $line_item_wrapper->field_imagethumb = $imagethumb;
  $line_item_wrapper->field_infobulle = $infobulle;

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using the wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save the order again to update its line item reference field.
  commerce_order_save($order);

And this is what i have:

  EntityMetadataWrapperException : Unknown data property
  commerce_webform_nid. dans EntityStructureWrapper->getPropertyInfo()
  (ligne 339 dans
  C:\xampp\htdocs\drupal\sites\all\modules\entity\includes\entity.wrapper.inc).

I have the same thing when i replace 'commerce_webform_nid' by simply 'nid' and the script stop. If i delete the line with 'commerce_webform_nid', then the exception is on the line after. So my question is: How can i achieve that? How can i assign the values that i getted to properties of the newly added line item? Thanks.
PS: When i delete the lines where there is the problem, the script works, and there is a new line item in the cart, but obviously without the values that i want to get.


texts: adding extra tab to user's profile using hook

texts:
I am trying to add a Send email tab to all user's profile using hook_menu(). However, it's not working. My custom module name is page_callback_test and here's the code in it.

function page_callback_test_menu() {
$items['/user/%user/email_user'] = array(
    'title' => t('Send email'),
    'page callback' => '_send_email_touser',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    );

return $items;

}

function _send_email_touser(){
    return t("let's send email to this user");
}


texts: Facets: Show more and Show less functionality

texts:
I am interested in a "Show more" and "Show less" functionality in facets like on this page http://ethicshare.org/publications/ethics?sc=publications
How can I do that?I am using search api.
thanks


texts: Create a drop down list of pages created using a specific content type

texts:
I've created a 'Galleries' page using a field collection so a user can create an infinite number of image links to individual 'Gallery' pages. The individual 'Gallery' pages are created seperately using a different content type.

I need to create a drop down list in the 'Galleries' content type field collection which lists all of the individual 'Gallery' pages which have been created. I've achieved this by adding a Node Reference field into the field collection on the 'Galleries' page which references all of the 'Gallery' content types.

This is as far as I've got, but can't figure out if or how I can use the drop down list values to somehow get the url of the selected pages and output it through the 'Galleries' template page.


texts: How to create new markers into a Google map with click?

texts:
I want to add a marker on click event and add it into exact location where user clicked on map.

Can't use any of the official examples which eventually return nothing.

My current module specific js code is as follows (just trying to build it step by step):

(function ($) {
  Drupal.behaviors.gmapPage = {
    attach: function(context, settings) {

      // Get map object / instance
      var map = Drupal.gmap.getMap($('.gmap-gmap').attr('id'));

      // Is this available in some other way?
      console.log(map); // Prints Drupal.gmap.map, but map != Drupal.gmap.map

      google.maps.event.addListener(map, 'click', function (e) {
        console.log(e.latLng);
      });

    }
  };
})(jQuery);

Everything else is fine but cannot create any functionality for the map.
Such an easy development task which seems so unbelievably challenging...

And this is purely for the front-end /ui - this question isn't about how to save location, load them into map etc. back-end related.

UPDATE:

I've added following script just for testing purposes:

(function ($) {
    Drupal.behaviors.gmapPage = {
        attach: function(context, settings) {

          // Get map object / instance
          var map = Drupal.gmap.getMap(settings.gmap.auto2map.id);
          // Following works although e is undefined
          // if 'ready' is changed to 'click' nothing happens
          map.bind('ready', function (e){
                console.log(e, 'map is ready');
          });

       }
    };
})(jQuery);


texts: Constraint on paragraph field not working

texts:
Here is a very simple code:
1-My constraint plugin (MyConstraint.php)
/**
 * @Constraint(
 *   id = "MyConstraint",
 *   label = @Translation("Never Validated", context = "Validation"),
 *   type = "string"
 * )
 */
class MyConstraint extends Constraint {
  public $message = "error %value";
}

2-My constraint validator (MyConstraintValidator.php) [=>addViolation in all cases]
class MyConstraintValidator extends ConstraintValidator {

  public function validate($items, Constraint $constraint) {
    dpm("I am displayed");
    $this->context->addViolation($constraint->message, [
              '%value' => 10
            ]);
    return;
}

3-My constraint added to my bundle
function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if($bundle=='my_bundle'){
      $fields['my_paragraph_field']->addConstraint('MyConstraint', []);
    }
}

Result:
1-The dpm message 'I am displayed' is displayed
2-The entity is saved without any validation error
Notes:
-I have other constraints which are working well, If I test one of them (on my_bundle), the violation of this working constraint will be displayed but not the one with the code detailled here.
-The problematic constraint is added to a paragraph field... I suspect the problem is coming from there
-Nothing in the error logs.
I am looking for a hint to where to look.


texts: How to set multiple list values via Entity Metadata Wrapper?

texts:
Field creation code:

if (! field_info_field(MY_FIELD_NAME)) {

    field_create_field(array(
        'field_name => MY_FIELD_NAME,
        'type' => 'list_integer',
        'settings' => array(
            'allowed_values' => some_allowed_values(),
        ),
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ));

    field_create_instance(array(
        'field_name' => MY_FIELD_NAME,
        'entity_type' => MY_ENTITY_NAME,
        'bundle' => MY_ENTITY_BUNDLE_NAME,
        'widget' => array(
            'type' => 'options_select',
        )
    ));

}

Setter code:

//posted options are list values keys e.g (3,4)
$wrapper->{MY_FIELD_NAME}->set(array_values($values['posted_options']));
//not work too:
$wrapper->{MY_FIELD_NAME}->set($values['posted_options']);
$wrapper->{MY_FIELD_NAME}->set(array($values['posted_options']));
//in for loop
$wrapper->{MY_FIELD_NAME}[] = $option_key;

Error:

  EntityMetadataWrapperException: Invalid data value given. Be sure it
  matches the required data type and format. in
  EntityMetadataWrapper->set()

or

  Fatal error: Cannot use object of type EntityValueWrapper as array

It works only when I set single value:

$wrapper->{MY_FIELD_NAME}->set($option_key);

This is not related to: Using entity metadata wrapper with custom entity type

because this is different field type.

Found solution:

   field_create_field(array(
        'field_name' => MY_FIELD_NAME,
        'type' => 'list_integer',
        'settings' => array(
            'allowed_values' => options_values(),
        ),
        'default_widget' => 'options_select',
        'default_formatter' => 'list_default',
        'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ));

    field_create_instance(array(
        'field_name' => MY_FIELD_NAME,
        'entity_type' => MY_ENTITY_NAME,
        'bundle' => MY_ENTITY_BUNDLE_NAME,
        'widget' => array(
            'type' => 'options_select',
            'formatter' => 'list_default',
        )
    ));


texts: Dynamic menu with latest Article in drupal7

texts:
I'm a bit new to Drupal environment. I'm trying to develop a demo site for CMS application. Now I'm facing a difficulty to create a dynamic menu for showing taxonomy-wise latest Article. Can I do it with any existing module (Muchomenu, OM Menu etc.,)

Thanks....


texts: Draggable table: drupal_render, render, both yield an empty string for "#weight" types?

texts:
I am attempting to implement a draggable table in a Drupal 7 module. Whenever I invoke either render() or drupal_render on my element of type #weight, an empty string is returned. The table does render and I am able to drag the rows, but cannot see the weights. I cannot figure out what I am doing wrong: I've explored some core Drupal components that follow the same pattern (of invoking drupal_render on a #weight type element) and nothing is jumping out at me.

My form begins here:

$table_header = array_map(t, array('Order', 'Item', 'Manage'));
$form['table'] = array(
    '#theme' => 'mymodule_kw_table',
    '#header' => $table_header,
    '#rows' => $my_rows // array(string)
);

hook_theme() is implemented as such:

function mymodule_theme()
{
    return array(
        'mymodule_kw_table' => array(
            'render element' => 'form',
            'function' => 'mymodule_table'
        )
    );
}

Finally, mymodule_table() looks like this:

function mymodule_table($variables)
{
    $table_data = $variables['form'];
    $table_id = uniqid('tb');

    $rows = $table_data['#rows'];

    for ($i=0; $i < count($rows); ++$i) {
        $weight = array(
            '#type' => 'weight',
            '#title' => t('Order'),
            '#default_value' => $i,
            '#delta' => 1,
            '#attributes' => array('class' => array($table_id . '-weight'))
        );

        $rows[$i] = array(
            'data' => array_map(render, array($weight, $rows[$i], 'abcd placeholder')),
            'class' => array('draggable')
        );
    }

    $table = theme('table', array(
        'header' => array_map(t, array('Order', 'Item', 'Manage')),
        'rows' => $rows,
        'attributes' => array('id' => $table_id)
    ));

    $table .= drupal_render_children($table_data);

    drupal_add_tabledrag($table_id, 'order', 'sibling', $table_id . '-weight');

    return $table;
}


texts:
I am not sure how this works, hence need a little help. I am fetching some nodes using db_select and rendering this in a foreach loop in a custom template file. I would give a hint of my code :

$nodes = db_select('node', 'n')
// Some fields...
// Some conditions...
// ->execute();
$nodes = $nodes->fetchAll();
return theme('my_custom_callback', array('nodes' => $nodes));

Now I get this $nodes in my tpl file and print them to the design. But what I want is to have the Drupal default pagination effect (probably using the PagerDefault facility). I have come accross many examples of the use of PagerDefault but I am not sure how to render the pagination in my tpl file.

Please note using a Drupal view or a table theme is not an option in my case.

Help appreciated...


texts: How to make the submit button not appear on form unless an option is selected from radios?

texts:
I have a form with three form elements:

'#type' => 'radios' element having two options (Yes or No),
'#type' => 'submit' &
'#type' => 'checkbox'

When the user lands on the form page, he should only see the radios element first and can see the checkbox & submit elements only if he selects an option from radios element.

Is there a Drupal way to do this using the Form API?


texts: Export current gutenberg content for page entered in the visual editor as JSON

texts:
I'm using Gutenberg and various custom content types like blog post, person, article, etc. I want it so when a user creates an article it automatically fills the page with a preset set of blocks with placeholder data, or data that came from custom fields for that content type.
I do see that there's a page template section https://www.drupal.org/docs/8/modules/gutenberg/page-templates that you can set for each content type. But instead of manually writing the JSON for the template I want to be able to take the content I've already entered and export it to JSON so I can paste it into that field.
Is it possible to export content from the Gutenberg visual editor to JSON so I can use it as a template for content types?
Update: I do see that content from gutenberg is stored in the database like so

This is the body text for node three

asdf

Test

Test

But I'm not sure how to turn that into a useable format for the page template.


texts: Can I pass variables from more specific template/preprocess function up to less specific?

texts: I need to display a node as a block, so I went with the most obvious way and created a view with a display block and this very node in it. But now I need to style it and I can't pick up the proper template. block-views.tpl.php looked great, but being in this template I do not seem to have access to view's variables anymore, have I? Basically I need a place where I could have access to view's variables and control over the look of the block. If I could just pass variables up the chain, that would be great...


texts: How can I print current user role in Twig?

texts:
I'm trying to get my user role thanks to a function in my theme.theme file.

function theme_get_user_role(){
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
}

then in my view :

{% set roles = theme_get_user_role() %}
{{ dump(roles) }}

But I have this error :

  Twig_Error_Syntax : Unknown "theme_get_user_role" function. dans
  Twig_ExpressionParser->getFunctionNodeClass()

What do I miss ?


texts: Click event not always fireing in Drupal behaviors

texts:
I'm having a strange problem with a form. Sometimes I have to click the submit button twice to make it submit my form. It also seems to work if I click outside the form before I click submit. The form is built inside a module with FORM API and is submitted with an ajax request. I have some js attached to the form so I can make some client side validation before the ajax call is run. This is what my js code looks like:

(function ($) {

Drupal.behaviors.mymodule = {
attach: function (context ,settings) {

    // Cache the form object
    var $form = $("#mymodule-form", context);
    var $submitButton = $('input[type="submit"]', $form);

    // Use once so we dont attach submit multiple times
    // Use off to remove any existing submit handler
    $form
        .once('mymodule')
        .off('submit')
        .on('submit', function(e){
            e.preventDefault();
            var $form = $(this);

            $(function () {
                $('#mymodule-form').submit(function () {
                    if($(this).valid()) {
                        $submitButton.trigger('submitmyform');
                    }
                });
            });

        });

        $(document).ajaxComplete(function(e, xhr, settings) {
            $('#mymodule-form').resetForm();
            $('#edit-mymodule-submit').replaceWith( "<div id='mymodule-confirmation'>TACK FÖR DIN ANMÄLAN</div");

        });

         // Run validation on $form object.
        jQuery.validator.setDefaults({
            debug: false,
            success: "valid",
        });

        $('#mymodule-form').validate({
            rules: {
                mymodule_name: {
                    required: true,
                },
                mymodule_length: {
                    required: true,
                },
                mymodule_suite: {
                    required: true,
                },
                mymodule_email: {
                    required: true,
                    email: true,
                },
                mymodule_phone: {
                    required: true,
                },
            },
            messages: {
                mymodule_name: {
                    required: "lorem ipsum",
                },
                mymodule_length: {
                    required: "lorem ipsum",
                },
                mymodule_suite: {
                    required: "lorem ipsum",
                },
                mymodule_email: {
                    required: "lorem ipsum",
                    email: "lorem ipsum"
                },
                mymodule_phone: {
                    required: "lorem ipsum",
                },
            },
        });

}

};

})(jQuery);

This is what my code looks like for the submit button:

    $form['mymodule_submit'] = array(
       '#type' => 'submit',
       '#value' => t("SEND!"),
       '#ajax' => array(
           'callback' => 'mymodule_form_callback',
           'wrapper' => 'mymodule-form',
           'event' => 'submitmymodule',
        ),
     );

Can anyone see what's wrong with this code?


texts: How do I convert a pre-existing site to a Composer-managed application?

texts:
The latest Drush 9.x version recommends that Drupal 8 sites will be built using Composer, with Drush listed as a dependency. However, when you install Composer and Drush globally per step #1 on http://docs.drush.org/en/master/install and then proceed to step #2 Installing Drush Launcher and then try to run Drush on a pre-existing Drupal website (e.g. drush --version), then you will get:

  Drush Launcher Version: 0.6.0
  The Drush launcher could not find a Drupal site to operate on. Please do one of the following:

  Navigate to any where within your Drupal project and try again.
  Add --root=/path/to/drupal so Drush knows where your site is located.

How do I get around this problem, and make Drush work with pre-existing Drupal sites?


texts: How to flip order of Privatemsg thread from ASC to DESC?

texts:
When an individual private message thread is viewed, it displays the thread messages from oldest to newest, followed by the "Reply" field. I'd like to show the "Reply" field first, and then the thread messages from newest to oldest. How can I reverse the order of the page in this way? I cannot find anything in the code that would point me toward something to re-theme it in a descending order instead of ascending.
Something like this:

[REPLY FIELD]
[Message on Jan 6 2017 at 11:30am]
[Message on Jan 6 2017 at 11:05am]
[Message on Jan 6 2017 at 10:00am]
[Message on Jan 5 2017 at 11:45am]

...instead of the current layout/ordering, which is like this:

[Message on Jan 5 2017 at 11:45am]
[Message on Jan 6 2017 at 10:00am]
[Message on Jan 6 2017 at 11:05am]
[Message on Jan 6 2017 at 11:30am]
[REPLY FIELD]


texts:
How do I use GROUP BY to display the result by group (email)?
this is my file .php

<?php
/**
 * Created by PhpStorm.
 */
namespace Drupal\gestion_contact\Controller;
use Drupal\Core\Controller\ControllerBase;
class GestionContactController extends ControllerBase
{
    public function admin() {

        $result = db_query("SELECT * FROM {contact}");

            $node = $result->fetchAll();

        return array(
            '#theme' => 'gestion_contact',
            '#nodes'=> $node,

        );
    }
    public function delete($id)
    {

        db_delete('contact')
            ->condition('id_contact', $id)
            ->execute();
        drupal_set_message(t('Your form has been deleted'));

        $result = db_query("SELECT * FROM {contact}");

        $node = $result->fetchAll();
        return array(
            '#theme' => 'gestion_contact',
            '#nodes' => $node,

        );
    }
    public function afficher()
    {

        $result = db_query("SELECT * FROM {contact} WHERE vu = :vu",
            array(':vu' => 'false'));
        $node = $result->fetchAll();
        return array(
            '#theme' => 'nouveaux_contact',
            '#nodes' => $node,
        );
    }
}


texts:
I have a content type in which i created flie type field and text type field.I uploaded the pdf file and wrote 'link' to text field.
I have copied the link from uploaded file and with the use of ckeditor given the link to the text 'link'. Now when i click to text 'link' then the pdf file get opened. But the problem is if we look at the url it says 'www.example.com/sites/default/files/ADMISSION_FORM.pdf'. which is not correct and secured i think. it shud be somelike 'www.example.com/node/35/ADMISSION_FORM.pdf'.
  Can anyone who knows tell me the fact....??????Thank you!


texts: I am new to Drupal and unsure how to add a module to a custom content type. I am currently trying to add the Field Quiz module to a custom content type on Drupal 8. Is it possible for someone to explain how I can do this?


texts: How to create a pair of dates (date_combo) using the Form API?

texts:
The Date module provide a field type called date_combo that allows a date feld to collect both a start date and an end date.

It works as expected when I use the GUI to create a content type with a date field an tick the box for the field setting saying: "Collect an end date" (i.e. you get an extra date field for the end date on the form to create new content).

I want to use the the date_combo content type when I construct a form using the Drupal API.  So far, I've inspected the form that is created by the GUI, and tried to duplicate this.  But I am getting errors complaining about undefined indices in the form.  For example:

Notice: Undefined index: #field_name in date_combo_element_process() (line 259 of .../sites/all/modules/date/date_elements.inc).
Notice: Undefined index: #bundle in date_combo_element_process() (line 261 of .../sites/all/modules/date/date_elements.inc).
Notice: Undefined index: #entity_type in date_combo_element_process() (line 262 of .../sites/all/modules/date/date_elements.inc).
Notice: Undefined index: #language in date_combo_element_process() (line 263 of .../sites/all/modules/date/date_elements.inc).
Notice: Undefined index: #field_parents in field_widget_field() (line 577 of .../modules/field/field.form.inc).

This is what I've tried so far:

  $form['datepair']['arrdep'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'class' => array(
        0 => 'field-type-datestamp',
        1 => 'field-name-rbg-unixtime',
        2 => 'field-widget-date-text',
      ),
    ),
    '#weight' => 1,
    '#tree' => TRUE,
    '#language' => LANGUAGE_NONE,
    LANGUAGE_NONE => array(
      0 => array(
        '#entity_type' => 'node',
        '#bundle' => 'rbg_booking',
        '#field_name' => 'field_rbg_unixtime',
        '#language' => LANGUAGE_NONE,
        '#field_parents' => array(),
      ),
      '#entity_type' => 'node',
      '#bundle' => 'rbg_booking',
      '#field_name' => 'field_rbg_unixtime',
      '#language' => LANGUAGE_NONE,
      '#field_parents' => array(),
    ),
    '#entity_type' => 'node',
    '#bundle' => 'rbg_booking',
    '#field_name' => 'field_rbg_unixtime',
    '#field_parents' => array(),
    '#access' => TRUE,
    'arrdep' => array(
      '#title' => t('A pair of dates:'),
      '#description' => t('Description'),
      '#type' => 'date_combo',
      '#theme_wrappers' => array(
        0 => 'date_combo',
      ),
      '#size' => 8,
      '#default_value' => array(
        'value' => $date,
        'value2' => $date2,
        'timezone' => 'UTC',
        'timezone_db' => 'UTC',
        'data_type' => 'datestamp',
      ),
      '#date_timezone' => 'UTC',
      '#element_validate' => array (
        0 => 'date_combo_validate',
      ),
      '#date_is_default' => TRUE,
      '#date_items' => array(
        'value' => $date,
        'value2' => $date2,
        'timezone' => 'UTC',
        'timezone_db' => 'UTC',
        'data_type' => 'datestamp',
      ),

    ),
  );

Guidance regarding how to make use of he date_combo construct by means of the Form API will be much appreciated.


texts: current_path() inside theme_menu_link returns previous path

texts:
I am trying to hide/show menu links based on my current page.  I have added the following snippet into my template.php file under mytheme folder.

/**
* Implements theme_menu_link().
*/
function mytheme_menu_link(array $variables) {
   $path = current_path();
   debug($path);
   //Do things based on $path

}

I have observed a very strange output of $path value. I will try to illustrator will a table

Time        |    Url          |   displayed $path value
   1        |    mysite/link1 |   none
   2        |    mysite/link2 |   link1
   3        |    mysite/link3 |   link2

It looks like the "current_path()" function call inside my mytheme_menu_link always returns the previous path. I have spent a full day googling and didn't see any case that is similar to mine.

Can someone tell me what is the possible cause and how I can avoid it?

Thanks!

PS: I have another call for current_path() inside mymodule_block_list_alter function and that one works correctly.


texts: Why does user column name has UNIQUE Constraint?

texts:
I got aware that the column name in TABLE users has a UNIQUE Constraint, when I tried to register a 2nd user with the same username : it returned a `integrity constraint violation 1062 duplicate entry '' for key 'name'.

Lets' say 2 of my customers called "John Doe" want to create an account : Ths 2nd one could not then ?!

So I made a quick SQL fix

ALTER TABLE `users` DROP INDEX `name`

I'd like to be sure it's not a very bad idea for some reasons ?

Config : this is a Drupal Commons distro


texts: How to preload generated styles and scripts?

texts:
I'm trying to preload my main css and js files - these files are generated using the AdvAgg module.

I've tried using the hook_preprocess_html in a theme and in a module, but in the $variables['page']['#attached']['html_head_link'] array, the styles and scripts aren't there.

What is the best way to access these file details, so I can create the necessary rel="preload" links?


texts: How can we make the summary field auto expand on load?

texts: We have an admin page with a summary and body. The summary is auto collapsed but we want it to be automatically expanded on the page load like below in the image.


texts: How can I add a custom attribute to a link field?

texts: For analytics/tracking purposes, I would like to add a custom attribute to a link field. Is there a way to add an additional text field to the link, similar to the title attribute field?


texts: How to print preprocess_html variables in page.tpl

texts:
I have variable in template.php to use in different files like page.tpl, but written this in preprocess_html function as below, how can i print this in page.tpl and html.tpl file.

mytheme_preprocess_html(&$variables){
      $variables['xyz'] = $xyz;
}

In page.tpl file, I tried with print $xyz; but it is not printing, where as I can able to print in html.tpl file this variable. Initially tried to add my code in preproces_page function, but I can't able to get in html.tpl file in this case.


texts: Trouble with Feeds Import CSV on Localhost

texts:
I'm using feeds node importer to import a csv file on my disk. It seems like no matter what I do, select the file from file system or put in the path for the file. I always get Error Message "Resource is not a file or it is an empty directory".

my localhost is at /var/www
Drupal 7 Folder: /var/www/drupal7
I stored the file at /var/www/drupal7/sites/default/files/feeds/bsif.csv
so I put the file path as public://drupal7/sites/default/files/feeds/bsif.csv
but it's not working


texts: How to validate fields with the Rules module?

texts:
I have created a Rule with the Rules module to validate the form on submission.

I try to compare the values of two fields to ensure one not higher than the other. But I couldn't find the appropriate Rules Actions to stop the form submission and prompted an error message.

Please advise.

Event: After saving new content of type Article

Condition: Data comparison
Parameter: Data to compare: [node:field-price-A], Operator: is greater than, Data value: [node:field-price-B]

Actions: ??


texts: Webform conditional calculation depending on selected options count

texts:
Users register for a conference via a webform. There are options for choosing a city [mandatory] and 1-4 dates [at least 1 date has to be checked]. E.g. user checks NYC + 2015-08-07 and 2015-09-01.

The price for the conference bases on the days count: if all 4 days has been checked = X USD; if 1, 2 or 3 of 4 days = Y USD/day.

Now, I have to calculate the price based on total count of checked dates and send it to the user in confirmation e-mail. How to do it?


texts: Programmatically exclude one of multiple fields views

texts:
I'm using hook_views_pre_render to change the output of a view. The view outputs an entity_reference field of a paragraph called field_date. This paragraph contains two date fields, a begin date and an end date (I'm not using the daterange module of drupal 8 core).

The field_date in the view is [hidden]. Multiple field settings is set to display all values in same row with a simple seperator. It is used in a Custom text field to output with other fields like so:

{{ field_date }}

{{ field_discipline }}

{{ field_afbeelding }}

{{ title }}

{{ field_korte_omschrijving }}

{{ field_event_locatie }}

The date output looks like this:

Wed, 01/17/2018 - 20:00
Wed, 01/17/2018 - 23:00,
Mon, 02/19/2018 - 20:00
Mon, 02/19/2018 - 21:00

With the code below I can read the target_id of a multi field entity_reference to a  paragraph.

foreach ($view->result as $i => $val) {
  $dateArray = $val->_entity->get('field_date')->getValue();
}

This code will output all target_id of the results the view gives. In one particular case the ouput is.

target_id: 41
target_id: 52

So two fields, with these ids I load the paragraph to see what values they have and find out I don't want to output the target_id: 52 field, I only want to show the date in January so target_id: 41. How can I exclude it or hide it from this hook without changing the values for good?

My complete hook is:

function hook_views_pre_render($view) {
    if ($view->id() == "view_id" && $view->current_display == 'view_display') {
        /* CHECK IF DATE IS IN THIS MONTH ELSE DELETE */
        // Get a node storage object.
        $node_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
        $dateArray = $val->_entity->get('field_date')->getValue();
        foreach ($dateArray as $iDate => $valDate) {
            //Get target id
           $targetId = $valDate['target_id'];
           //Load target paragraph
           $targetParagraph = $node_storage->load($targetId);
           //Get this month
           $resultMonth = explode('-', $targetParagraph->get('field_begin_datum')->value)[1];
           //If result month is not same as group month, hide output
           if($resultMonth != $month){
               //don't output this paragraph
            }
            else{
               //output this paragraph
            }
        }
    }
}

Thanks in advance


texts: If multiple routes match a path pattern, how can I tell which one would be used?

texts:
If multiple routes are returned by something like the following:
$route_provider = \Drupal::service('router.route_provider');
$found_routes = $route_provider->getRoutesByPattern('collection/%collection/items');

How can I find out which of those routes would be used if a path matched that pattern?
According to the docs:

getRoutesByPattern() returns a route collection of matching routes. The collection may be empty and will be sorted from highest to lowest fit (match of path parts) and then in ascending order by route name for routes with the same fit.

In my case, two routes with the same fitness are returned in alphabetical order:

Would the first or second one be considered more fit?


texts: Accessing hreflang in a preprocessor or twig layer

texts:
How do I access this link in either the twig layer or a preprocessor in Drupal 8. I need to modify to edit the hreflang.  Thanks

<link href="http://www.drupal.com/au" rel="alternate" hreflang="au" />


texts:
I have a taxonomy with 4 categories; each category has child-categories beneath them.

This taxomony term is exposed in a view filter, but I get a combination of the parent and child categories in the resulting dropdown list options. What I actually want is just the parent-categories listed and not the child-categories.

Can anyone help?


texts:
Hi Drupalites I need some help.

1.I was using relationship to output authors personal info associated with a piece of content which i did successfully. so i was trying something else but i didnt succeed.

I created a content type called State-Capital which has a list of of States and their respective capitals and I created another Content type called Misc Project which had different project details like Cost,Project Approve and State.Now i was trying to link the state field to output the capital associated with the respective state in Misc Project content type but i cudnt.The field name for States in both content type are same.Pls help.

I am trying to learn panels so wanted to know if there is any link or material for the same


texts: Create database fields to an existing table when installing a module

texts:
I'm new to drupal and I need some help.

I created a new module with name user_extra. Which create necessery table when Installing the module.

But I also need to insert some database field in 'users_field_data' table ('user_extra_id' and 'user_office')

In baseFieldDefinitions I wrote all necessery database table fields for user_extra table.

 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    // Standard field, used as a unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
        ->setLabel(t('Unit ID'))
        ->setDescription(t('The unit ID.'))
        ->setReadOnly(TRUE)
        ->setSetting('unsigned', TRUE);

    $fields['uuid'] = BaseFieldDefinition::create('uuid')
        ->setLabel(t('UUID'))
        ->setDescription(t('The unit UUID.'))
        ->setReadOnly(TRUE);
        .
        .
        .
    $fields['user_info'] = BaseFieldDefinition::create('string')
        ->setLabel(t('User Info'))
        ->setDescription(t("The User Info"))
        ->setSetting('max_length', 255)
        ->setDisplayOptions('form', array(
          'type' => 'string_textfield',
          'weight' => 10,
        ))
        ->setDisplayConfigurable('form', TRUE);
     return $fields;
     }

When I install the module it inserts all values that I define in baseFieldDefinitions.

But I also need to create 'user_extra_id' and 'user_office' in 'users_field_data' table with setDisplayOptions and setDisplayConfigurable options.

This is the commenting that I made in entity file

/**
 * @ContentEntityType(
 *   id = "user_extra",
 *   label = @Translation("user extra"),
 *   handlers = {
 *     "storage" = "Drupal\user_extra\UserextraStorage",
 *     "storage_schema" = "Drupal\user_extra\UserextraStorageSchema",
 *     "access" = "Drupal\user_extra\UserextraAccessControlHandler",
 *     "list_builder" = "Drupal\user_extra\UserextraListBuilder",
 *     "view_builder" = "Drupal\user_extra\UserextraViewBuilder",
 *     "views_data" = "Drupal\user_extra\UserextraViewsData",
 *     "form" = {
 *       "default" = "Drupal\user_extra\Form\UserextraForm",
 *       "add" = "Drupal\user_extra\Form\UserextraAddForm",
 *       "edit" = "Drupal\user_extra\Form\UserextraEditForm",
 *       "delete" = "Drupal\user_extra\Form\UserextraDeleteForm",
 *     }
 *   },
 *   admin_permission = "administer user_extra",
 *   base_table = "user_extra",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *   },
 *   links = {
 *     "canonical" = "/admin/user_extra/{user_extra}",
 *     "add-form" = "/admin/user_extra/add",
 *     "delete-form" = "/admin/user_extra/{user_extra}/delete",
 *     "overview-form" = "/admin/user_extra/${user_extra}/overview",
 *     "edit-form" = "/admin/user_extra/{user_extra}",
 *     "collection" = "/admin/user_extra",
 *     "children" = "/admin/user_extra/{user_extra}/children",
 *   },
 * )
 */


texts:
I'm having trouble getting the entity browser widget to work correctly in a custom form. Just wondering if anyone has had any success in getting it working. I've got to the point the button is rendering, you can use the browser, select the media. The the media id is also attached to the hidden field the widget generates.

...from my digging around it looks like it never creates the right markup in the "current" div that get sent back from the ajax request that triggers on "process"

Code below...

      $form['entity_browser_wrapper'] = [
      '#type' => 'container',
      'widget' => [
          '#title' => t('Entity Browser'),
          '#field_name' => 'entity_browser_wrapper',
          '#field_parents' => [],
          '#required' => false,
          '#parents' => ['entity_browser_wrapper'],
          '#tree' => true,
          '#id' => 'edit-entity-browser-wrapper',
          '#type' => 'details',
          '#open' => true,
          'entity_browser' => [
              '#type' => 'entity_browser',
              '#entity_browser' => 'document_browser',
              '#cardinality' => 1,
              '#entity_browser_validators' => ['entity_type' => ['type' => 'media']],
              '#process' => [
                  ['\Drupal\entity_browser\Element\EntityBrowserElement', 'processEntityBrowser'],
                  ['\Drupal\entity_browser\Plugin\Field\FieldWidget\EntityReferenceBrowserWidget', 'processEntityBrowser'],
              ]
          ],
          'current' => [
              '#theme_wrappers' => ['container'],
              '#attributes' => [
                  'class' => 'entities-list',
              ],
              'items' => [],
          ],
      ],
  ];

This is based off a question I found in the entity browser issues https://www.drupal.org/node/2816881. I've looked into the suggestions that were posted and have come up blank.

Thanks


texts: Link static HTML, Javascript and CSS3 in a Drupal Site

texts:
I am trying to have collaborative development of a HTML5 web app which people could navigate too through my drupal site. I was planning on putting the html, JS and CSS3 files in my sites/default/files folder and just passing a link. I am curious how i perform to things

How can I put an alias over the html file so i can have url mysite/demo
also I want to block people from reading my JS and CSS3 files so the source code is just not purely out in the open is there a way to do this.

I know inspect html on most browsers give you a lot but I do not want them to find my .js file and then request that and have my source code.

Any assistance or guidance would be very helpful


texts:
In Drupal 6, if you had a content type with the system name "stock-photo", you could override it using:

node-stock-photo.tpl.php

How do you do this in Drupal 7?


texts:
I'm working a on a project that needs to have one of their submodules enable but not both.

I was wondering if I can have an or statement  in the .info so the user would not enable both submodules.

The Drupal 7 documentation "Writing module .info files (Drupal 7.x)" does not talk about this.


texts: Attachment added through hook_mail_alter() is making no effect

texts:
I'm trying to add one pdf attachment to the mail sent on webform submission. I'm using hook_mail_alter() to add attachments to the mail.
This is the code I am using.
function webfpdf_mail_alter(&$message) {
$attach = genpdf($message['params']['message']);
$message['params']['attachments'][] = $attach;
dpm($message);
return $message;
}
The output message shown by dpm() shows attachment, but the email doesn't contain attachments.
This is the output of dpm().
attachments (Array, 1 element)
0 (String, 568525 characters ) Content-Type: application/pdf; name="Webform-...
Content-Type: application/pdf;
 name="Webform-submission.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename="Webform-submission.pdf"

cSA4NS4wNCAwIDAgMzMuNzMgMjguM......
..../****base64data*****/.....
..... ;
body (Array, 1 element)
headers (Array, 7 elements)
MIME-Version (String, 3 characters ) 1.0
Content-Type (String, 24 characters ) text/html; charset=UTF-8
Content-Transfer-Encoding (String, 4 characters ) 8Bit
X-Mailer (String, 27 characters ) Drupal Webform (PHP/5.3.29)
Return-Path (String, 35 characters ) enquires@xxxxxxx.org
Sender (String, 35 characters ) enquires@xxxxxxx.org
From (String, 28 characters ) "LESS" <support@xxxxxx.com>

Can anyone help me to fix this?


texts:
I was needing to add a default value to a text field that disappears when you click on the field.

I did found this question :

How to add default text that clears on focus to a form in Drupal?

However, my knowledge is pretty limited as far as creating hooks so I'm a little lost as to the solution being drawup up here.

Could someone please point me in the right direct?

Cheers!


texts:
I'd like to apply several panes without title to a panel (in Drupal 7).

I can select Override title and leave the input field blank, but this still leaves the wrapping HTML.

Can I completely exclude a title?


texts: Hide some of the fields of user profile of profile2 module

texts:
I am using Drupal 7 profile2 module for creating user profile and Organic group module for group managemnet.

I have user status field in user profile, and there are two options(radio button) for visibility of profile field like 1. Visible in Group 2. Invisible.

Visible in Group is selected then any group member can see the user status

Invisible then no one can see the user status field

Now I want to know that is there any way to unset the profile field during viewing. Is any hook calling during user view event ?

I have also the code that checks whether user being viewed and logged in user are member of same group or not


texts: How to update the version of AngularJS using module configuration

texts:
I'm trying to build an application using Drupal and AngualarJS. When I download and enable the drupal-angualar module(https://www.drupal.org/project/angularjs) it shows the top version as 1.3.4, but I want to use the latest angular version(1.5.8).

How can I update the angualar version to latest?


texts:
I need to ask the user for an 8-digit number within a yaml form.

the number I need is 12345678 and goes is this layout: 1.234.567-8

is it possible to ask the user for this 8-digit number field and display it as 1.234.567-8 ?

ideally the field would be rendered to the user as: _ . _ _ _ . _ _ _ - _ while it's being filled.

thanks in advance


texts: Drupal 7 Bartick Theme Title shows below body

texts: Drupal newbie here.  I have set up a site using Drupal 7 and the Batik theme.  On some pages the title shows up below the body and on some others it displays on top as I wish.  Is there a setting I am missing?  At this point it is mostly default settings.


texts: References by title (not nid) while creating nodes via PHP code

texts:
does anyone know how to create node reference while creating node programmatically? I mean - using TITLE and TYPE, not nid.

I am creating nodes via python script and user is prompted for title of parent node. Nobody's gonna tell you NID in that case. But content type and part of title should be enough.

If there is no way of doing that in Drupal - I am gonna make my own function to fetch all nodes that fits criteria and go further if there's only one or prompt for choosing proper one if there's more than one..

I'll be happy if there's already something that handles my task.. :)

My current code with doing that by NID:

    $n = new stdClass();
    $n->type="project_release";
    node_object_prepare($n);
    $n->title = "Kaboom [".date(YmdHis)."]";
    $n->language = LANGUAGE_NONE;
    $n->uid = 1;
    $n->body[$n->language][0]['value']="12345";
    $n->body[$n->language][0]['summary']="123457890";
    $n->body[$n->language][0]['format']="filtered_html";

    $n->field_release_project[$n->language][0]['nid']=85;
    $n->field_project_release_notes[$n->language][0]['value']='AaAAAAAA...';

    $path = 'remotely_added_at_'.date('YmdHis');
    $n->path = array('alias'=>$path);
    if($n=node_submit($n)) {
        node_save($n);
        echo "</br>Node with nid ".$n->nid." saved\n";
    }

Cheers


texts: How to get multifield(subfields value) in rules Drupal 7

texts:
i use the multifield module with multifield table display in my entityform.

So, in my entityform i have one multifield type with 5 subfields.

How can i get subfield value in Rules?

Thanks


texts: How to get main menu to highlight the link to the current page?

texts:
My theme, Riley, highlights menu item of the page that you're on. (for example). I suspect this is a function of Drupal and not specific to the theme. First question: is this generally true?

If the answer to the first question is no and it is theme specific, then I can try to ask the theme makers the next question. Otherwise, my next question is, when I have multiple menu links that link to the current page, it will highlight the last link. How can I get it to highlight the first link instead? I am comfortable modifying PHP code.

For example, Menu Tab 1 contains link to current page P1 and deep within Menu Tab 2 also contains a link to P1, then it will only highlight the P1 link in Menu Tab 2.

Any thoughts / suggestions would be appreciated!

Setup: Apache 2.2, PHP 5.3, Drupal 7.34, PostgreSQL 9.2


texts:
Hello i was wondering if anyone could suggest anything for me with this problem i have with my forms. (add/node) Ive turned CCK and all my modules off but still when i go to the node/add page the form is taking ages to load (20secs+) even for a simple submission form with no fields etc.

Generally my website http://onlinebanter.com runs ok and i do my best to keep my module lust down.

Is there any code or diagnostic tools i could use to see why my forms are talking so long to load.

Thanks


texts:
I have created a taxonomy term "tags". If I use the url to access the content with that term I have the following error.

403 Forbidden
You don't have permission to access /drupal/tag/sport on this server.

"sport" is a taxonomy term and tag is the taxonomy.

Even if I am admin or anonymous user.


texts: Updated to 8.9.1 getting 'content_moderation_state plugin does not exist' message

texts: Updated a drupal project to 8.9.1, all seemed to go smoothly. After i run drush updb and I got the following message. Anyone know what's this about and how to resolve? All other update were run successfully.


texts: How do I extend a protected core function?

texts:
In core\modules\menu_link_content\src\Plugin\Menu\MenuLinkContent.php is a protected function getEntity().

I want to "make" this function public. Can I do this by extending the class MenuLinkContent? And if so, how do I extend this class (in a custom module)?

Here is what I already got (location: modules/my_module/src/Plugin/Menu/MenuLinkContentHelper.php):

<?php

namespace Drupal\my_module\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkBase;

/**
 * Provides the menu link plugin for content menu links.
 */
class MenuLinkContentHelper extends MenuLinkContent {

  /**
   * {@inheritdoc}
   */
  public function my_function() { // should override getEntity()

    // give me the return of getEntity() as $value

    return $value;
  }

}

But I don't know if that works or how I can make this accessible.

Please help!


texts: How to attach image from a list of predefined images?

texts:
Anyone had this? I have a custom content type and I want to give an option to attach an image from a list of predefined images (in my case - a list of product series logotypes). The admin interface would be a simple dropdown of logotype labels:

- None -
Series 1
Series 2
Series 3

How would I then process the selection and convert it into a real image?
What would be the best practice here?

Regards,
Artur


texts: How to configure my local Drupal site to contact my local Apache Solr server?

texts:
I installed Apache Solr server on my local machine and installed the Apache Solr Search module on my Drupal 7 site. When I configure the module and click submit an error message appears:

  Your site was unable to contact the Apache Solr server.

But when I go to http://localhost:8983/solr/#/ my Solr admin opens.


texts: How to print a table create with views, using a submit button below the view?

texts:
I created a custom template for my views (table) and I inserted a button below the table.

By clicking on that button I would like the table to be shown in a new page, from which that table can be printed.

Or to say it in another way: I want to embed to new page via such button.

How can I do this?


texts: Get User ID from a Profile Page to use in a View

texts: I'm creating Views blocks on profile pages such as drupalsite.com/users/testuser. I need to display blocks such as "Test User's Posts" and "Test User's comments." What is the best way to get the User ID of the profile pages' subject in order to filter the content based on this User ID?


texts:
I can't figure out how to insert a javascript function inside a node.

It's a countdown script that uses an external js file and i need the function to be called from within a node. (each node will have a different countdown target date)

I set the input filter to php but it didn't work.
All it does is printing the js file content as node content

I put the js file in a folder inside sites/all/scripts and here's how i use :

<?php include('sites/all/scripts/countdown.js'); ?>

Any ideas ?

thanks a lot


texts: Computed Twig solution not showing in preview?

texts:
I'm trying to understand Twig.

This is what I have got

{{ (data.number_1) * (data.number_2) }}

Why doesn't the preview page calculate the solution?


texts: Generate PDF from custom fields, and link from Views page

texts: I have a list of records that are presented to end-users in a View. That works fine. What I want to do is generate a printable PDF from custom fields so that users can print out a nicely formatted profile page and hand the printout to someone else. Does anyone know if this is possible?


texts: How to bootstrap a custom script and retrieve the session object?

texts:
I'm writing a custom script that requires a proper Drupal 8 user session to work. This is the current version:

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = __DIR__;
define('DRUPAL_DIR', $drupal_root);

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->handlePageCache($request);
$kernel->prepareLegacyRequest($request);

// get session handler and retrieve session details
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$session_id = $session_handler->getId();
$logged_in = (bool) $session_handler->read($session_id);

// inspect values
var_dump($request->getSession());
var_dump($session_id);
var_dump($logged_in); exit;

I'd expect $request->getSession() to return something, $session_id to be the Drupal's session id, and the $logged_in variable to be truthy. Instead I keep getting this output:

NULL string(0) "" bool(false)

Update 1: I executed this on a browser, which I have an active session with my Drupal. This script is placed in a subfolder of the Drupal installation, so it should not be a cookie path issue.

Update 2: Added var_dump($request->getSession()) to the script.


texts:
I am trying to show the label through css on the CKEditor (attached image). The wired thing is that the body of the editor is an iframe were my external stylesheet is loaded so the toolbar is not included.

Any ideas of how to work this out? Thank you

[![.cke_button__media_label {
  display: inline !important;
}]


texts: How do I keep multiple sites in sync using drupal-composer/drupal-project

texts:
What is the correct process to keep local and production sites in sync when using drupal-composer/drupal-project. Most of the solutions online only discuss updating one site and not dev, staging and production properties.

This is the current process I am using

put live site in maintenance mode
run composer update drupal/core --with-dependencies -vvv

I run this on both local and production servers
I noticed that this does not sync alpha and beta contributed modules
I noticed that running 'composer update' from the root of the project updates core and all contrib modules

run drush updb

I run this on both local and production servers

I then commit changes to git from the local site

I just want to find out what otheres are doing to keep multiple sites in sync


texts: How to use Apache Solr as data source for a view

texts:
Is it possible to use data indexed in Solr as the data source for a specific view?
I already tried installing the search api, search api page, entity api, ctools, search api solr and the views api.

I already created a server and an index which uses solr:

But the only fields that I get are node fields:

I'm expecting to get the fields from documents that I indexed in Solr. How do I do that in Drupal, is there a specific module that would allow me to make use of the fields that already exists in Solr as the fields for a view?


texts: REST server or other way to do a password reminder

texts: I see in the services 3 module that there is not a password reminder functionality yet although it has been discussed. What I want to know is whether there is any other way that I can call for the password reminder to be triggered from an external source (i.e. using HttpClient in Android to post direct to the form). I am building an android app and have just about everything in the login/register process complete except for a password reminder functionality. Are there any examples of using java to post directly to a drupal form available?


texts: Drupal 7 appending class in uc attribute option radio button

texts:
I have this code inside mymodule_form_alter:

     foreach ($form['attributes'] as $att) {
        foreach ($att['#options'] as $option => $value) {
  // Get the name of the option without the price or price adjustment -> string before coma
            $optionName = explode(",", $att['#options'][$option], 2)[0];
            if (strpos($optionName, '+') !== false) {
                $att['#options'][$option]['#attributes'][] = array('class' => array('my_class'));
            }
        }
    }

Unfortunately

  $att['#options'][$option]['#attributes'][] = array('class' =>
  array('my_class'));

Displays unexpected error, I tried different syntax but no success. Any help much appreciated

  Update 27/09/2017

I tried to do this by using after_build I get no errors but it isn't working

// Inside hook_form_alter
 $form['attributes']['#after_build'][] = 'addToCartFormEditQuantity_after_build';

 function addToCartFormEditQuantity_after_build(&$element, &$form_state)
{
    // Each renderable radio element.
    foreach ($element as $attribute) {
        foreach (element_children($attribute) as $option) {
            var_dump($attribute[$option]);
      // Get the name of the option without the price or price adjustment -> string before coma
            $optionName = explode(",", $attribute['#options'][$option], 2)[0];
            if (strpos($optionName, '+') !== false) {
                $attribute[$option]['#atrributes']['class'] .= 'single-double';
            }
        }
    }

    return $element;
}


texts: Best way to unpublish a node, given the nid, while bypassing any node update hooks?

texts:
To unpublish a node, I set status=0 and call node_save(). Unfortunately, this invokes the Geocoder module and it sends a request to the Google API for a geocode that I already have. There is apparently no way to turn this off.

I am looking for an alternative to node_save() that does not trigger this behavior or any other hooks, for that matter.

(btw, for fields I am achieving this with field_attach_update, but to unpublish I need to update the node itself)


texts: How do I call php functions with parameters from Js in Drupal 8?

texts:
I am attempting to create/read nodes from a JS file (the nodes are created in response to Js events from a library). The PHP functions to create/read the nodes have been created and require field data as parameters. How can I run these functions from a JS file and pass the required data as parameters? I am willing to relocate/rewrite the functions in a new PHP file if required.

I cannot use routing/controllers/API endpoints as I would need to pass parameters as slugs - some parameters are strings and may contain slashes which are not supported by routing
The generation and submission of data is based on a JS library rather than Drupal forms, so I cannot use Drupal Ajax forms and pass my parameters through that. Without forms, Ajax callbacks have no support for parameters.
I am not sure if this Ajax request is an option with Drupal - if it is, how would I structure the 'url' in the Ajax request to get a certain php file from my module?


texts:
I'm stuck on a necessary component for a website I'm working on.

I've got a content type called "Photograph" which has a variety of fields including one for "Date", which includes a variety of entries including just the year, or the year and month, or the full date.

My problem is that I cannot select a date earlier than 2013, which is a problem because some of these photographs date from 1848 on up. That leaves me with the option of a calendar selection, or by entering the date itself, which doesn't work for ease to visitors. So I'd like to use the selection option (with a focus mainly on years), but how do I edit the select options to include the years that I need included?


texts: Display the fields of the current taxonomy with an exposed form

texts:
I'm using the Taxonomy term view.
I expose the "Has taxonomy term" filter to my users in a block.
I want to display the title and the fields of the current taxonomy even when a term has been typed in the exposed form.
However, apparently, when the view is filtered, views no longer finds the argument in the url since the url contains an all?tid=.
Do you know how to do it ?
For example:
I have a tag "Tag 1", with a description "Description Tag 1".
If I go to the mysite.com/tags/tag-1 page, it works, I come up with the replacement patterns to get what I want.
But, when I filter the view with the exposed form, I get url mysite.com/taxonomy/term/all?tid=tag+1, and the replacement patterns no longer work. For "%1", I get "all". For other tokens, I got errors.


texts: Entity with ECK: image is there, but it doesn't render properly

texts:
I've created a new entity type with ECK and added an image field. All is well: I can create an entity and add the image, on the edit interface it shows up properly. However, when I display the entity, the image gives a 404 because for some reason, I end up with s like this:

<img src="<root of Drupal instance>" />

Do you have any idea on how to debug / fix this?


texts: How restrict a constraints to a content type?

texts: I would like to create validation for a several fields on a content type to check if they each have unique values from each other. The part I'm struggling with is how to add the constraint for just my content type, and not all node entities. So far I'm using hook_entity_type_build() to add: $entity_types['node']->addConstraint('UniqueSizes', []); Is there a way to restrict this to only my content type?


texts: Force new articles to have tags (term + subterm) associated with it

texts:
previous question

I have a site where articles need to be classified as, apple, banana, cranberry, etc....

Each category has sub-cats like apple - 1, apple - 2, ... banana - 1, banana - 2 ...

Now apples can have 10 subs and banana can have 200 or something like that.

I already make a vocabulary using taxonomy of all the terms and subterms.

What I need to do is have it so that users submit articles and it must have a category and sub-cat associated with it.

I want to do it this way so that I can have an index page of all apple articles, or just apple - 1, or banana - 2's ... etc.


texts:
How do I programmatically change the value of Date's datetime field attached to an entity in Drupal 7, to the sites current time and timezone.

For example:

$entity = entity_load('node', 99);
// modify entity date
$entity->field_date_example = ...
entity_save($entity)


texts:
I'm learning the new caching system. For testing purposes I have turned off Page Cache and Dynamic Page Cache.

I've set a custom block with the following:

<some code>
$build_array = $view_builder->view($referenced_entity, self::VIEW_MODE, self::LANG_CODE);

$build_array['#cache']['contexts'][] = "route";
$build_array['#cache']['keys'] = ['mymodule_panels_blocks','taxonomy_term', $term->id()];

This is for displaying an eck entity with an image that is attached to a taxonomy term.

The expected behavior is that when I point the term to a different eck entity, the taxonomy term is invalidated.

When I check the full list of tags (using http.response.debug_cacheability_headers: true) I see my taxonomy term listed (taxonomy_term:209).

So it would seem I'm all set up. Yet when I change the eck entity to a new one, click Save, then click View, I see the old image still.

When I flush the render cache, I see my new image.

Isn't the invalidation of the taxonomy term automatic when the term is saved? Or do I have to write a hook to invalidate the taxonomy term when it changes?


texts: No visible files in DIR (site/default/files) throught the IMCE

texts:
I have a problem with IMCE manager:

I upload my files throught CONTENT -> FILES, all files are visible there (sites/default/files).
I check (Home » Administration » Configuration » Media » IMCE) for sites/default/files path and permissions. It's all OK.
But when I use IMCE "Add Link" button to link an uploaded file, and choose to pick it up from server... I see nothing (except 0 files using 0 bytes of unlimited quota) in file browser. Navigation tab also shows: /sites/default/files

Files folder has 0777.
Uploaded files can be also opened by ULR.

Thanks!


texts:
I want to save file programmatically in public path, and I want to know how can I get Public Directory path in Drupal 8. In Drupal 7, I would use the following code.

drupal_realpath(file_default_scheme() . '://')

What is the equivalent in Drupal 8?


texts: feeds importer tamper double importing image

texts:
Using feeds import with tamper to split up images at a | our database has thousands of products and only some of them have an image and then some have a second image (a room view of the product) and the images arent tracked in the data.

anyways the build of the url to retrieve the image is: http://domain.tld/imgs/flooring/Manufacturer/IemNumber.jpg|http://domain.tld/imgs/flooring/Manufacturer/IemNumber-room-view.jpg

when importing displays with a second image it works fine along with displays with no images however when importing displays with only one image it puts in two of the same image instead of ignoring the second image that it cant find as I would expect it to


texts: Error in php snippet using tokens: Show profile field if it isn´t empty

texts:
I have this core profile field in Drupal7: profile-curso-basico.
I want it to be shown in the user´s profile  only if the field has information in it (it´s a deprecated field, but some old users have data in it, and migrate modules didn´t import it properly, because it´s a hardcoded list).

I´m using panels, token and Display Suite modules.
At the profile page, I have this panel with a special coded DS field, that has dinamic information using tokens.

If I just paste: Mi Curso: %user:profile-curso-basico I get the field information properly, but I want to show it only if profile-curso-basico field isn´t empty.

So I thought of this (the input type is PHP, so I can paste some php code):

<?php if (!empty(%user:profile-curso-basico)): ?>
%user:profile-curso-basico
<?php endif; ?>

And I´ve got this error:

Parse error: syntax error, unexpected T_LNUMBER, expecting T_PAAMAYIM_NEKUDOTAYIM in /home/liga/public_html/modules/php/php.module(80) : eval()'d code on line 9

What´s wrong with that snippet? Maybe I shouldn´t add tokens into (!empty( )) ?
How may I change that in order to work? Thanks!!


texts:
I've been using Aegir to install Atrium sites without a hitch. Users self register through Aegir to spawn their own open atrium sites. Today I noticed new atrium sites failed to install. A week ago this worked fine and as far as I know nothing has been changed with core content/modules. I did some comparisons in looking at the task log between the failed install and a successful install (from a week ago). The simplexml load and "Could not download project status information" is weird. Here's what I gathered so far. Task install log looks identical until near the end. The failed install shows the following after "downloading release history…":

Downloading release history from http://updates.drupal.org/release-history/drupal/6.x
simplexml_load_file(): 6.x:2: parser error : Specification mandate value for attribute http-e pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:2: parser error : attributes construct error pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:2: parser error : Couldn't find end of Start Tag meta line 2 pm.drush.inc:2103
simplexml_load_file(): s="http://www.w3.org/1999/xhtml">
simplexml_load_file(): ^ pm.drush.inc:2103
simplexml_load_file(): 6.x:12: parser error : Opening and ending tag mismatch: p line 11 and body pm.drush.inc:2103

This goes on for several more lines - finally ending in the following error:

Could not download project status information from http://updates.drupal.org/release-history/drupal/6.x

This compares to This compares to the successful site task install log here:

Downloading project drupal to /tmp/drush_tmp_1368706259 ...
Downloading drupal-6.28.tar.gz was successful.
Md5 checksum of drupal-6.28.tar.gz verified.
Verifying signature for svn version control engine.
Verifying signature for bzr version control engine.
Project drupal (6.28) downloaded to /var/www/vhosts/site.com/platforms/atrium-1.0/drupal-6.28.
Project drupal contains: - 1 profile: default - 6 themes: pushbutton, min... (Expand)

The diff analysis looks similar again for many more lines, then shows the following error for the failed install log:

WD form: Illegal choice 5 in Roles allowed to use this profile element.
WD form: Illegal choice 6 in Roles allowed to use this profile element.

The rest of the task log for the failed install shows typical Aegir behavior of dropping the database and deleting directory.Searching through my general site logs, or when I run cron, I get

"Unable to fetch any information about available new releases and updates."
I also get that error when I try to manually run cron
Also a few other things like:

Warning: include() [function.include]: Unable to allocate memory for pool. in theme_render_template() (line 1079 of/var/www/vhosts/site.com/hostmaster-6.x-1.4/includes/theme.inc).

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

The "unable to fetch information about new releases..." error is weird and similar to the Aegir error on the failed install task log.
Unfortunately I don't know where to start. I'm wondering if this is a write permissions issue with drush, or php version issue. It;s starnge that it's happened suddenly, so maybe Aegir changed something on the fly. Don't know... Any thoughts? Thanks!


texts: Commerce : adding optional insurance block to shopping cart form : ajax callback

texts:
Customers will be purposed an optional insurance in the shopping cart, calculated as a percentage of Cart Total. I added this feature as an editable field in a footer view of the shopping cart, and I'm trying to setup ajax callback to update the cart.

EDIT (@people who already read the question) : I solved the initial bugs, so this is a clean update. You can jump to item 7 if you don't want to read the full implementation...

What I've done so far :

Created an insurance taxonomy, each term is an insurance option with a % decimal fields (in order to allow insurance options changes at any time).
Added this taxonomy to the order fields with a term reference field "Insurance" .
Created a very simple view block called cart_field_assurances with that Insurance field, with editable format.
Installed Cart View Override, cloned shoppping cart form and set that clone as shopping cart
Created a views-view--commerce-cart-form-assurances.tpl.php template with :

print $rows;
print views_embed_view('cart_field_assurances', 'block');

Moved insurance view before #edit-actions div with Jquery

var insurance = $('.view-id-cart_field_assurances').detach();
insurance.prependTo('#edit-actions');

Removed action buttons, added ajax to the field, declared insurance price component

function vts_insurance_form_views_form_cart_field_assurances_block_alter(&$form, &$form_state, $form_id) {
  $ajax = array(
    'callback' => 'vts_insurance_cart_refresh',
    'progress' => array('type' => 'throbber', 'message' => ''),
  );
  $form['field_order_assurances'][0]['field_order_assurances']['und']['#ajax'] = $ajax;
  //Hide buttons
  $form['field_order_assurances'][0]['actions']['submit']['#attributes']['class'] = array('hidden');
  $form['actions']['#attributes']['class'] = array('hidden');
}

//ajax callback
function vts_insurance_cart_refresh(&$form, &$form_state) {
  //Load the order
  $view = $form_state['build_info']['args'][0];
  $order_id = $view->result[0]->order_id;
  $order =  commerce_order_load($order_id);
  //set new value
  $order->field_order_assurances['und'][0]['tid'] = $form_state['values']['field_order_assurances'][0]['field_order_assurances']['und'][0]['tid'];
  commerce_order_save($order);
}

//insurance price component
function vts_insurance_commerce_price_component_type_info() {
  return array(
    'insurance' => array(
      'title' => t('Insurances'),
      'display_title' => t('Insurances'),
      'weight' => -10,
    ),
  );
}

Set up a rule : Before saving a commerce order, calculate the insurance amount and add it to total as an Insurances price component

To illustrate, this is the shopping cart form, with the optional insurance field below

The question

How to refresh the display of "Cart Commerce Order total" shopping form view (and its price components of course) in vts_insurance_cart_refresh ajax callback ?


texts:
I would like to implement a reminder functionality on a website, where a (anonymous) user can define a time for a (pop-up) reminder to fire automatically. Think of it as a digital egg timer, where you are reminded after some 5 minutes that your eggs are hard boiled... ;-).

My initial idea was to save the due time in $_SESSION['reminder'] and let Drupal check at each cron run whether the reminder is due. However, this approach fails because hook_cron operates on a global level and therefore does not recognise $_SESSION variables. On the other hand, saving the due time in, say, a node field does not make sense either: Drupal would find all due reminders and fire a pop-up which would be visible to every user currently on the site! So summing up, I need to find a way to initiate a process at a given time that is restricted to a particular session. Can anyone give me advise on how to go for this one?

Also, I need the reminder to pop up at the very top of all running applications in order not to be missed by the user. This is obviously something that all pop ups would like to achieve, so a user would probably have to give special pop-up permissions to this site. But how can I program such a pop-up, and what special settings are required? Alternatively, I could display the reminder as a (browser independent) system message, like the messages when receiving an MS Outlook email for example. Does anybody know whether and how this can be easily achieved?

I am sorry that this request is a bit vague, but it's really more about the general strategy and I haven't reached the level for detailed questions yet. So I would highly appreciate your ideas and experiences in similar applications in order to get inspired.


texts: How to show fields in different regions?

texts:
I've tried the Display Suite module, which only comes with regions per display suite layout template (also the extra module did not change this) which basically just changes the body/ content region... making the themes regions available was not possible. It still would be a bit overkill for what I want anyways.

All I want to do is make a field from within any content type available to be put in any region. No blocks. No views.

Just as the display suite module offers a new column in the manage display tab "region" with a drop down to pick which region the field shall be put in.

How come there is no module like that?

Thanks!

Edit: I've read this thread but I want to do it without views and if possible without blocks.


texts:
I'm using Drupal 7 with views 3.

I have defined a custom handler for a field and is working on my development machine. When I revert same view in live environment I am getting issue of broken handler, even the handler class s present.

Thanks in advance for your help.


texts: Is it possible to theme node add form in drupal 7

texts:
I am using zen drupal-7 sub theme. I have created a content type named edison. I need to change the node add form for the user. I've tried adding page--node--add--edison.tpl.php in template.php. I used the following code:

if (isset($variables['node'])) {
  $variables['theme_hook_suggestions'][] = 'page__node__' . str_replace('_', '--', $variables['node']->type);
}

When the $variables['theme_hook_suggestions'] variable is printed, it looks like this:

Array (
  [0] => page__node
  [1] => page__node__add
  [2] => page__node__add__edison
  [3] => page__node__edison
)

The custom .tpl is not overriding the page.tpl.php.


texts: Colorbox - Only display some of the images in a gallery

texts:
I've got colorbox set up and working great, but I'd just like to do one little thing that I can't figure out.  I want to have a colorbox gallery of, for example, a dozen photos, but select three to display on the page.  Once you click one of the three photos on the page, it opens up the colorbox, which allows you to click through all 12 photos.  Is this possible with Colorbox and Drupal 7?

EDIT: I'd like this to be a fix that I can use on a lot of different pages with varying numbers of photos.  Sorry for the ambiguity.