texts:
I'm building a multistep register form in a custom module. I'm using profile2 module to save other custom fields. I want to let the users choose an image from their computers. This is the code that I use to upload the picture that saves in the file_managed Drupal table but without the user uid because at this point I don't create the user.

$form['empresa']['logo_empresa'] = array(
        '#title' => t('Logo de la empresa.'),
        '#type' => 'managed_file',
        '#description' => t('Tamaño máximo 3Mb y formato aceptado jpg,jpeg o png'),
        '#upload_location' => 'public://',
        '#upload_validators' => array(
        'file_validate_extensions' => array('png jpg jpeg'),
        'file_validate_size' => array(3*300*300),
        ),
);

When all fields are OK I submit the form and create the user as follows:

function empresas_registration_signup_form_submit($form, &$form_state) {

$nombre = $form_state['storage']['field_nombre_contacto'];
$apellidos = $form_state['storage']['field_apellidos_contacto'];
$mail = $form_state['storage']['email'];
$comunidad_autonoma = $form_state['storage']['field_comunidad_autonoma'];

$provincias = $form_state['storage']['field_provincia'];
$razon_social = $form_state['storage']['field_razon_social'];
$cif_nif = $form_state['storage']['field_cif_dni'];
$telefono = $form_state['storage']['field_telefono'];
$web = $form_state['storage']['field_web'];

$municipios = $form_state['storage']['field_municipio'];
$poblacion = $form_state['storage']['field_poblacion'];
$direccion = $form_state['storage']['field_direccion'];
$codigo_postal = $form_state['storage']['field_codigo_postal'];

$razon_social = $form_state['storage']['field_razon_social'];
$clave = substr($razon_social, 0, 3);
$cif_nif = $form_state['storage']['field_cif_dni'];

$usuario = $clave.$cif_nif;
$password = password(8);
//$imagen = $form_state['values']['field_logo_empresa'];

$roles = user_roles();
$newuser = array(
        'name' => $usuario,
        'pass' => $password,
        'mail' => $mail,
        'status' => 1,
        'roles' => array('7' => 'empresa'),
        'access' => time(),

);
$existing_user = user_load($usuario);
if (!$existing_user->uid) {
    $account = user_save(null, $newuser);

    $profile = entity_create('profile2', array('type' => 'empresa'));
    $profile->uid = $account->uid;

    //Datos a guardar para el perfil

    $profile->field_nombre_contacto[LANGUAGE_NONE][0]['value'] = $nombre;
    $profile->field_apellidos_contacto[LANGUAGE_NONE][0]['value'] = $apellidos;
    $profile->field_razon_social[LANGUAGE_NONE][0]['value'] = $razon_social;
    $profile->field_cif_dni[LANGUAGE_NONE][0]['value'] = $cif_nif;
    $profile->field_direccion[LANGUAGE_NONE][0]['value'] = $direccion;
    $profile->field_codigo_postal[LANGUAGE_NONE][0]['value'] = $codigo_postal;
    $profile->field_telefono[LANGUAGE_NONE][0]['value'] = $telefono;
    $profile->field_web[LANGUAGE_NONE][0]['value'] = $web;
    $profile->field_poblacion[LANGUAGE_NONE][0]['value'] = $poblacion;
    $profile->field_comunidad_autonoma[LANGUAGE_NONE][0]['value'] = $comunidad_autonoma;
    $profile->field_provincia[LANGUAGE_NONE][0]['value'] = $provincias;
    $profile->field_municipio[LANGUAGE_NONE][0]['value'] = $municipios;

    $profile->save();

    $account->profiles['empresa'] = $profile;
    entity_save('user', $account);
    drupal_goto('user');

}
}

My question is: How could I set the fid from the table and assign it to the user?


texts:
Running on Debian I have updated Drush to version 7:

composer global require drush/drush:7.*

composer global update

But the command 'drush --version' still tells me:
Drush Version : 6.2.0

I have looked everywhere but didn't find a solution.

Thanx for any help.


texts:
I have a News page which links to a bunch of news articles and I'm looking to print the header of the News Page on the individual articles.

The field_get_items doesn't return anything right now.  Any advice would be greatly appreciated!

if ($node->type == 'article') {
         $news_header = field_get_items('page', $node, 'group_header'); print_r($news_header);

             //$url = file_create_url($node->field_header_image['und'][0]['uri']);
             //echo '<img src="' . $url . '" width="100%">';
            // }
        }


texts: What is the twig template name for a node edit form?

texts:
In Drupal 8, what is the twig template name for a node edit form for a custom content type called for example "device".

For a default node we use node-edit-form.html.twig
So what is the edit template name for a custom content type ?

I would appreciate your help.
Thank you !


texts: New content pane (in view) not showing up for adding to panel

texts: Added new content pane as part of my view. Even after saving, and clearing the cache, this pane is not showing up on the available panes list when adding content to Geary type panel/column in Drupal 7. Could this be a configuration issue?


texts:
I'm using the Workflow module in Drupal 8 and I saw this checkbox on the "add a state" screen (/admin/config/workflow/workflows/manage/help/add_state):

  Default revision When content reaches this state it should be made the default revision; this is implied for published states.

What exactly is meant here by "default revision"?  Why is it implied for published states?


texts: How to display user picture programmatically in a rule (User Relationships)

texts:
Starting from the code in a previous question, I am now trying to post a user picture in a rule that displays a relationship between two users (User Relationships module.)

It is the requestees's picture I am trying to display (the $requestee variable is allowed)

Here is the code I have so far:

$imgpath = file_load(($requestee->picture[und][0]['uid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail', 'attributes' => array('class' => array('RequesteesPicture'))));
$link = l($image, "user/$requestee->uid", array('html' => TRUE));
print $link;

I see the placeholder for the pic. The link to the requestee's picture is correct and the image style is also correct. But the pic does not show.

What do I need to do to make the pic show up?

Thanks. :)


texts: How can i display the badges with username like stackexchange? I am using D6 and user badge and userpoints modules.


texts:
I have a case content-type that has an image_field. I have configured the field to use a default image in cases when no image is upload for a case.
I then try to render the image using the following code:

<?php $view = node_view($node); ?>

<?php print t('Publicerad'); ?>: <?php print date('d - M - Y', $node->created); ?>

    <?php print render($view['field_image']); ?>

If the case has a connected image then the field is rendered as expected, but in other cases nothing in displayed. When I check under recent log messages I see this:

Location   http://localhost/test/sites/default/files/styles/case_170x107/public/default_images/default_case_pic_0.png?itok=CWr6R4Rs
Referrer   http://localhost/test/search/node/case
Message    Unable to generate the derived image located at public://styles/case_170x107/public/default_images/default_case_pic_0.png.

I don't understand why it fails to generate a style for my default image when it works fine with user supplied images.

I have checked the permission on the folder and everything seems fine, so I really don't understand why this is not working?

Notice that all other images that is uploaded gets their image styles generated without any problem. The error only gets triggered in case of a default image connected to the field_image field.


texts: Why /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction is taking so long?

texts:
I'm profiling drupal 8 website in New Relic

Report shows me that method:

  /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction

takes ~2sec.

This method is called in:

  \Drupal\Core\Render\Renderer->doRender

Code related to execution:

// Build the element if it is still empty.
if (isset($elements['#lazy_builder'])) {
  $callable = $elements['#lazy_builder'][0];
  $args = $elements['#lazy_builder'][1];
  if (is_string($callable) && strpos($callable, '::') === FALSE) {
    $callable = $this->controllerResolver->getControllerFromDefinition($callable);
  }
  $new_elements = call_user_func_array($callable, $args);
  // Retain the original cacheability metadata, plus cache keys.
  CacheableMetadata::createFromRenderArray($elements)
    ->merge(CacheableMetadata::createFromRenderArray($new_elements))
    ->applyTo($new_elements);
  if (isset($elements['#cache']['keys'])) {
    $new_elements['#cache']['keys'] = $elements['#cache']['keys'];
  }
  $elements = $new_elements;
  $elements['#lazy_builder_built'] = TRUE;
}

Method code:

 /**
   * #lazy_builder callback; renders a form action URL.
   *
   * @return array
   *   A renderable array representing the form action.
   */
  public function renderPlaceholderFormAction() {
    return [
      '#type' => 'markup',
      '#markup' => $this->buildFormAction(),
      '#cache' => ['contexts' => ['url.path', 'url.query_args']],
    ];
  }

 /**
   * Builds the $form['#action'].
   *
   * @return string
   *   The URL to be used as the $form['#action'].
   */
  protected function buildFormAction() {
    // @todo Use <current> instead of the master request in
    //   https://www.drupal.org/node/2505339.
    $request = $this->requestStack->getMasterRequest();
    $request_uri = $request->getRequestUri();

    // Prevent cross site requests via the Form API by using an absolute URL
    // when the request uri starts with multiple slashes..
    if (strpos($request_uri, '//') === 0) {
      $request_uri = $request->getUri();
    }

    // @todo Remove this parsing once these are removed from the request in
    //   https://www.drupal.org/node/2504709.
    $parsed = UrlHelper::parse($request_uri);
    unset($parsed['query'][static::AJAX_FORM_REQUEST], $parsed['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
    return $parsed['path'] . ($parsed['query'] ? ('?' . UrlHelper::buildQuery($parsed['query'])) : '');
  }

I don't get it at all. This is basic method, no rocket science and 2 sec of execution :(

New Relic output:


texts: Where and how to conditionally redirect old aliases to new aliases

texts:
We are replacing a website with a new version. The domain is the same, but URL aliases in the new website are different.

In many cases, I can use an old alias to calculate its corresponding new alias. There are many thousands of old aliases, so I don't want to just use the Redirect module. I know how to write the calculations and how to check if a calculated new alias exists.

I need to know at what point I can intercept each incoming URL to calculate a new alias.

I also need to know how to redirect to the calculated new alias if it exists.

Concrete example:

A book chapter on the old site is at example.com/recent/secrets-to-success/10-knowing-when-to-quit. This chapter on the new site is at example.com/secrets-to-success/knowing-when-quit. The difference is (a) we no longer add the recent subfolder, (b) we've removed chapter numbers from chapter titles, and (c) we've changed which words are ignored when an alias is auto-generated.

When someone uses an old alias, I want to intercept it, calculate the new alias, check if it exists, and redirect to it if it does. This is only one example. There are several other ways of calculating, so there's some trial and error involved. But I know how to take care of that.


texts: Is it Inethical/Bad Practise to create a custom table and save content instead of using drupal fields?

texts:
I was going through the Drupal 8 and find that it offers a lot in terms of structural data. There are many modules that use this structure data to execute very important web tasks.
Like
Search engine optimization,
Feeds,
API etc.

As a developer for a quick fix, we often create some content and save it on a custom table using a custom module, instead of putting content into Drupal structure as node field. Though this will solve our problem for short span of time quickly.

So is it something we should never do in case of Drupal?


texts:
I have played with Menu Trail by Path and Menu Position, but none worked well with a Views-generated listing acting as a navigation menu.

Imagine the following scenario:

On the left side there is Views generated block of linked taxonomy terms.
When clicked, the link fills the main content area with a listing of nodes tagged with the given taxonomy term. The activated term link gets active-trail class - so far so good.
When you click a node link though, the node opens, but now - the active-trail is gone.

The complicating factor might be that my taxonomy is localized (each term has a translation within same vocabulary). But I believe there is a solution to that... Anyone?


texts: I am not able to assign a group to a node while creating it

texts:
We are using Drupal 7.39 and Services 7.x-3.12 .

We are also using organic groups 7.x-2.7 and while creating a node of type attendance (which is a group content). We are not able to assign a group to it.

We are passing the following parameters:

{
  "type": "attendance",
  "title": "Testing Attendance",
  "field_attendance_status":{
  "und":{
    "tid":3
  }},
  "og_group_ref":{
    "target_id":16
  }
}


texts: Remove items in taxonomy entity relation on node edit form

texts:
If a field on the node edit form is a entity relation to a taxonomy term vocabulary, I want the taxonomy terms be restricted on certain conditions. I don't know how to do it safely. I have tried it in hook_form alter(). Deep in the "array stack" of the form variable is the definition of the entity reference form field.

Is the only way to "hack" the "#process" array, or is there any object-oriented way to filter the items in the drop down element?
Is there any form "plugin" to filter the items in Drupal 8?


texts: Output a field on every second/third row in views

texts: Is it possible to output a certain views field on every nth row (loop) instead of every row?  Thank you


texts: Programmatically update Webform Submission by sid

texts:
I'm trying create/update Webform Submission programmatically. I already know how the create new submission by following the Drupal 8 API. Now I'm trying to build a update method, I refer to the Webform module source-code and API documents but couldn't find a solution. I guess they remove webform_get_submission webform_submission_update functions in Drupal 8.3 as-well.

$values = [
  'webform_id' => 'attendees_info',
  'in_draft' => FALSE,
  'uid' => $uid,
  'langcode' => 'en',
  'token' => 'at_'.$token,
  'uri' => '/webform/attendees/api',
  'remote_addr' => '',
  'data' => [
    'name' => $name,
    'email' => $email,
    'gallery_url' => 'gallery/'.$token,
  ],
];

$webform = Webform::load($values['webform_id']);
$is_open = WebformSubmissionForm::isOpen($webform);

if ($is_open === TRUE) {
    // Validate submission.
    $errors = WebformSubmissionForm::validateValues($values);

    // Check there are no validation errors.
    if (!empty($errors)) {
       return $errors;
    }
    else {
      // Submit values and get submission ID.
      $webform_submission = WebformSubmissionForm::submitValues($values);
      return $webform_submission->id();
    }
}

Above is my Submission creation code, I don't know how to do the update method. Is anyone face this issue before? Hope someone will help me on this, thanks.


texts: Why is my $node always null in my custom block (using plugin contexts)?

texts:
I am trying to make a block that gets the current node via Plugin Contexts.

But my $node is always null. Can anyone tell me why?

I am placing the block with the context module if that makes a difference?

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header' block.
 *
 * @Block(
 *   id = "header",
 *   admin_label = @Translation("Header"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE)
 *   }
 * )
 */
class ProductStickyHeader extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

    $node = $this->getContextValue('node');
    // $node is always null!

    return $build;
  }
}

Many thanks!


texts:
I'm new to commerce and I have a question. I'm building a website for a butcher, and he wants products to be sold per 100gr. I have the price in kilo and I allow decimal values for quantity.

The quantity field widget is a text box by default. I did some googling and found some things but i'm unable to get it work. I assume I need the commerce_cart_add_to_cart_form() function :)

I want to have a drop down with pre-defined values per 100 gram for example.

100 gram - 1 euro
200 gram - 2 euro
300 gram - 3 euro
....

1000 gram - 10 euro

Add to cart button

Any idea's? Or is there an easyer solution for this?

Thanks in advance


texts: How to disable new user registered email to admin

texts:
When a new user registers, there's an email sent to the admin in the form:

Subject: Account details for [name] at [site name] (pending admin approval)
Message: [Name] has applied for an account.
[profile URL]

How can I remove this email alert? The reason being, that I've created a customised message triggered by the Apply for role module.
Thanks.


texts: Automatic generate a parent category when adding a new node

texts:
I have a content type Artist and a content type Songs. Each artist has a number of songs. I want to be able when I add a new song to assign it to the artist that it belongs and then have a view of the songs from a specific artist. I don't want to do a seperate term in taxonomy for every artist I add. Can this be automatically? ex. When I add an artist, and then I add a song I want to be able to assign this new song to the new artist without me having to manually add a new taxonomy term for the artist and then assign this song to this taxonomy term...

I want my paths to look like this.
ex: artist/songallery  ----> artist/songname

Hope I made myself clear,
thank you in advance.


texts: Node's Preview when using Views module to render Node

texts:
I have been using Views module to render Node's Full content (using unformatted list of fields!). Seems that was not such a good idea.

Now when I preview the Node, I see the Teaser and Full content Entity view modes (instead a View with fields). So the actual problem is these teasers and Full content are not themed the way my View is.

Is there any workaroud except rebuilding the whole thing in Display Suite module?

THX!


texts: Private File System and Externally Modified Files

texts:
I have a D7 site that includes a few hundred nodes that have PDF attachments that use the core file field and the private file system. The site uses a custom module to dynamically watermark these PDFs and we're going through an update that requires each PDF to be updated to use a new layout.

In order to minimize downtime, what I was hoping to do was pull the site to a development environment, directly edit the PDFs that are stored in the private file system and then push the updated files and changes to the watermarking feature back to production.

All seemed like a good plan, but I'm finding that Drupal will no longer serve the updated files after they've been modified. No error messages in the logs (Drupal, PHP or server) and the site just times out when you request new files from /system/files/...

I haven't been able to find any documentation or relevant issues on the subject, but I'm wondering if Drupal's private file system is failing to deliver the file due to changes to the timestamp or file size?

Has anyone run into this before? I'm hoping there's a workaround that does not require that we update hundreds of nodes by editing and manually re-uploading each file one at a time.

Thanks much!


texts: I backed-up my site and now my views are broken

texts:
My site recently got deleted by a possible hack. I backed up the database and the folders, but now my views are not working; everything else works.

The fields are showing this in admin/build/views/edit/nameofview:

  Broken/missing handler: node_data_field_guru_photo > field_guru_photo_fid
      Broken/missing handler: node > title
      Broken/missing handler: views > nothing
      Broken/missing handler: node_revisions > body
      Broken/missing handler: node_data_field_guru_link > field_guru_link_url


texts:
I tried to customize the "password recovery" page under Drupal 7, based on this tutorial : http://www.absolutecross.com/tutorials/drupal/theming-the-user-account-page-in-drupal.
I did so for the register and edit page, and it works ok.

However, for this page, I run into a problem. When the page "/user/pass" (is that the standard url by the way ?) is called, I ran into an access denied page.

I browse through the permissions : nothing in there to allow/deny access to this page. I also use loginToboggan, disabled it for a while, to no avail.

Any idea of what I could I have overlooked ? I am lost...

Thank you.


texts: Cannot re-order the blocks of Drupal 7 site

texts:
This error happens just on my local server (I use the last version of Acquia Dev Desktop, kind of XAMP for Drupal), not on our remote servers:

I am suddenly unable to re-order the blocks of our site (Drupal 7.23). The drag-and-drop functionality is not working and entering the weight numbers manually either. I have researched this problem and tried all solutions posted (Aggregate JS, disable LightBox2, change the DB block fields from tiny to INT...).

We have a large number of files in our website, and in some regions they have reached the magic number of 127. Reading a few posts, I see this may be the problem when you have some DB fields defined as tiny, but after changing all the tiny (4) fields of the blocks table to INT(11) I do not see any change.

Any clue?

Thank you very much in advance.


texts:
I have the following in my module.

drupal_add_js(
    drupal_get_path('module', 'responsive_videos') . '/js/fluidvids.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'weight' => 10,
    )
);

For some reason, when this module is enabled, jQuery and jQuery Once get removed from the head and the JavaScript console logs many "Uncaught ReferenceError: jQuery is not defined". Can anyone clarify why this is happening, and how to fix it?

Here is the info file, responsive_videos.info.

name = Responsive Video
description = Creates a fluid responsive video from YouTube or Vimeo embedded iframes.
core = 7.x

And here is the module file, responsive_video.module.

<?php
/**
 * @file
 * Makes YouTube and Vimeo embedded iframe videos responsive.
 */

drupal_add_js(
    drupal_get_path('module', 'responsive_video') . '/js/fluidvids.js',
    array('scope' => 'footer')
);

The JavaScript file being added does not leverage jQuery, so I don't quite understand how or if it might interfere with jQuery being added to the page, but here is the source of the "fluidvids.js" file.

// http://toddmotto.com/fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js/
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory;
  } else {
    root.fluidvids = factory();
  }
})(this, function () {

  'use strict';

  var fluidvids = {
    selector: ['iframe'],
    players: ['www.youtube.com', 'player.vimeo.com']
  };

  var css = [
    '.fluidvids {',
      'width: 100%; max-width: 100%; position: relative;',
    '}',
    '.fluidvids-item {',
      'position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;',
    '}'
  ].join('');

  var head = document.head || document.getElementsByTagName('head')[0];

  function matches (src) {
    return new RegExp('^(https?:)?\/\/(?:' + fluidvids.players.join('|') + ').*$',     'i').test(src);
  }

  function getRatio (height, width) {
    return ((parseInt(height, 10) / parseInt(width, 10)) * 100) + '%';
  }

  function fluid (elem) {
    if (!matches(elem.src) || !!elem.getAttribute('data-fluidvids')) return;
    var wrap = document.createElement('div');
    elem.parentNode.insertBefore(wrap, elem);
    elem.className += (elem.className ? ' ' : '') + 'fluidvids-item';
    elem.setAttribute('data-fluidvids', 'loaded');
    wrap.className += 'fluidvids';
    wrap.style.paddingTop = getRatio(elem.height, elem.width);
    wrap.appendChild(elem);
  }

  function addStyles () {
    var div = document.createElement('div');
    div.innerHTML = '
x
';
    head.appendChild(div.childNodes[1]);
  }

  fluidvids.render = function () {
    var nodes = document.querySelectorAll(fluidvids.selector.join());
    var i = nodes.length;
    while (i--) {
      fluid(nodes[i]);
    }
  };

  fluidvids.init = function (obj) {
    for (var key in obj) {
      fluidvids[key] = obj[key];
    }
    fluidvids.render();
    addStyles();
  };

  return fluidvids;

});

fluidvids.init();


texts: I have a view with a grid displaying rendered entity of product list for my product display index. Is it possible to add a read more link to the product list display with a link to the product. I have tried to create this in several different ways, by creating a link in the content type fields, however that would require manual completion. I appreciate that if I was using fields in views I could add the link there. I'm hoping there is a solution to adding to the product list. I have also looked at adding it manually to node.tpl.php, but I am unsure of where to define the variable instead of $teaser. Many Thanks in advance.


texts:
When using a field collection feed import, I get this error.

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path: /batch?id=17839&op=do StatusText: OK
  ResponseText: Deprecated: Automatically populating $HTTP_RAW_POST_DATA
  is deprecated and will be removed in a future version. To avoid this
  warning set 'always_populate_raw_post_data' to '-1' in php.ini and use
  the php://input stream instead. in Unknown on line 0 Warning: Cannot
  modify header information - headers already sent in Unknown on line 0
  {"status":true,"percentage":"64","message":""}

I have researched this issue and statistically came up with this solution: change in php.ini always_populate_raw_post_data = -1

I have changed that and also restarted apache.

I still receive that error. Does anyone have any thoughts to this?


texts:
I am having trouble setting up free shipping on my Commerce project.  I added the Free Shipping module, but when I go to configure, I don't have any options.

The shipping costs for all of our products are absorbed by the manufacturer (who also drop-ships the product, so we don't care about FedEx, UPS, etc).  Therefore, I want to show a free shipping line item during checkout.

I installed the Shipping module (7.x-2.x-dev), and I don't see options to create Shipping Services or Shipping Methods.

How can I configure our store so all products are free shipping?  I watched a few screencasts, but none of them seemed to apply to what I'm wanting to do.


texts: Views Contextual Filters: Using node's URL alias as a conditional filter

texts:
I have Drupal content whose nodes have URL aliases;

/node/1 routes to /bar

I also have a View which passes a NID as a contextual filter:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

[selected radio] Provide default value

TYPE

[selected dropdown] Raw value from URL

PATH COMPONENT:

[selected dropdown] 1

[checked] Use path alias

View's Path is set for /foo/%

So:

/node/1 returns node

/bar returns node

/foo/1 returns view

/foo/bar returns a white screen

How do I allow the View to access the node's URL alias as a conditional filter?

Thank you


texts: How to Output Realtime Computed Field Value

texts:
I have created a computed field (computed_field module) and I'd like the calculated value of this field to be computed on the fly for each of my views results.
Specifically, I have a start time, and and end time for each "Offer" (content type) in my view. I have created a computed field that determines whether the current time is between the start time, and end time, and then outputs a string value of "now" or "ending_soon" or "starting_soon" or "default" (if it's outside the parameters). I'm doing this all because I need to use the contents of this calculated field as a path variable for custom map markers in a google map (different 'pins' for offers/deals that are happening now, vs ones that are happen earlier or later in the day).
inside my THEMENAME.theme file:
function computed_field_field_now_compute($entity_type_manager, $entity, $fields, $delta)
{
  // from the database:
  $timestamp = $fields['field_business_dates'][0]['value'] ?? "";
  $endtimestamp = $fields['field_business_dates'][0]['end_value'] ?? "";

  $now = gmdate('Y-m-d\TH:i:s\Z');
  $utc = new DateTimeZone('UTC');
  $startDate = new DateTime($timestamp, $utc);
  $endDate = new DateTime($endtimestamp, $utc);
  $nowDate = new DateTime($now, $utc);
  $startSwatch = date_format($startDate, 'B');
  $endSwatch = date_format($endDate, 'B');
  $nowSwatch = date_format($nowDate,'B');
  $cutOffSwatch = 22; // Note: 41.6 = 1 hour;
  $endingSoonTime = $endSwatch - $cutOffSwatch;
  $startingSoonTime = $startSwatch - $cutOffSwatch;
  $value = "default";

  if ($nowSwatch >= $startSwatch && $nowSwatch <= $endSwatch) {
    if ($nowSwatch >= $endingSoonTime) {
      $value = "ending_soon";
    } else {
      $value = "now";
    }
  } else if ($nowSwatch >= $startingSoonTime && $nowSwatch <= $startSwatch) {
    $value = "starting_soon";
  } else {
    // return default value
  }
  return $value;
}

As these calculations are time-sensitive, I've turned off caching with the hope that the values are calculated on the fly and displayed in my view. But they are not displayed in views, and don't seem to display at all unless I save each individual node first. As I have over 6500 nodes...I don't see this as feasible. How can I ensure that when a view needs to display the calculated field, that the calculation is executed and rendered?


texts:
Is it possible to show a numbered output to an unlimited value field (in the input form rather than the display).

Basically I have a field collection and I'd like to show by the side of each one entered a count, so if you write one it looks like

1 | field_one
  | field_two
  | field_three

Then if you added another it would look like

1 | field_one
  | field_two
  | field_three
2 | field_one
  | field_two
  | field_three

and so on...

I'm trying to think where you'd go about doing this, I can't see anything that counts out how many values it has when looking at the $form array in the page itself, and I wouldn't have thought it'd be something that you can do via a template file.

Can this be done?


texts:
I have a feature which contains fields for the user profile page. This is currently working in PROD.

In the dev site, I've updated the feature to include a new field, updated the version, and download a new TAR file.

In PROD, when I go to Update Module, and try to update the feature, an error message appears saying the feature is already installed.

Am I missing something here? Are features only expected to be installed once? Or do I need to manually remove the feature before updating?

Would it be better practice to create a brand new feature containing the one field?


texts: Can a Drupal view show some fields for one role and other fields for another role without having two page views?

texts:
I need to create a view showing the history of the users events. I need the authenticated users to be able to see part of the view, certain fields, and the admin to see all fields in the view. The fields are user_id, activity_id, title, status. I need the user_id and activity_id to be hidden from the authenticated user but not the admin. I know how to control the whole view but not fields in that way.

Has anyone tried to manage that? Is there a way to do this?


texts: I am trying to create a Features module and include my content types but not all of them are showing when I select "Content Types: node".  I am seeing about 80% of them.  Why would this be?


texts:
I couldn't come up with much constructive title, as
The Title could also be: Separate Voting system for Fields in same Node

In a Content Type I have 3 fields

Mind
Body
Soul

all are Longtext as in the picture below.

At the moment in this content type, I am using Plus1 Module with VotingAPI for vote, but this doesn't seem to fulfill my need.

What I am trying to acheive is to have 3 voting system, one for each field (Mind, Body and Soul), so, any individual can vote in any of these field.

I have tried using the Fivestar Module and adding it as field, but it breaks my Page Layout due to JavaScript Conflict. I will post that as different question.

My question is: is there any readymade module which can help me acheive this, so, I can have Voting system for Individual Field item and store the votes in Database.


texts: Adding custom layout to Omega child theme breaks grid system

texts:
I'm trying to create an new responsive layout in an Omega child theme. To do this I copied the grids variable from alpha.info into MYTHEME.info and added my layout (called 'narrower') based on the existing pattern:

grids[alpha_default][name] = Default (960px)
grids[alpha_default][layouts][fluid] = Fluid
grids[alpha_default][layouts][narrower] = Narrower
grids[alpha_default][layouts][narrow] = Narrow
grids[alpha_default][layouts][normal] = Normal
grids[alpha_default][layouts][wide] = Wide
grids[alpha_default][columns][12] = 12 Columns
grids[alpha_default][columns][16] = 16 Columns
grids[alpha_default][columns][24] = 24 Columns

settings[alpha_layouts_alpha_default_narrower_responsive] = '1'
settings[alpha_layouts_alpha_default_narrower_media] = 'all and (min-width: 480px) and (min-device-width: 480px), (max-device-width: 740px) and (min-width: 480px) and (orientation:landscape)'
settings[alpha_layouts_alpha_default_narrower_weight] = '0'

I also added a css file: MYTHEME-alpha-default-narrower.css

The problem I'm seeing is that none of the omega/alpha grid system css files are loaded (e.g. sites/all/themes/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-12.css)

Apparently others have had success with this (like here: How to add a new responsive Layout for large viewports to Omega Theme), so I'm not sure what I'm doing wrong.


texts:
I have a view with navigation set to paged, 12 items. I can see 12 items (there are way more available), but no pager. Googling this problem I found the following solutions that didn't work:

View uses Global: PHP fields (my view doesn't do that)

View is displayed in a block (my view is displayed in a page)

Changing pager id (tried everything from 0 to 5, also, this is the only pager on this page)

It's also not a styling issue, the pager is not in the markup. I didn't override any templates related to the view.

In other views, the pager works and I can also see it in the views preview. In this view, I can't even see it in the preview - this should prove that it's not a theming issue as well, am I right?

I tried displaying a "more" link, but that didn't work as well. Changing the navigation to "mini pager" also doesn't help.

The view is using a relationship to an entity reference, but that shouldn't be an issue IMO. Other than that it's a pretty ordinary view displaying some fields. Anyone have any ideas?

(Drupal 7, Views 3)


texts: A question about views and how to let sub menus link to the view like the main menu

texts:
I created a view, like products. The path is /products, and the normal menu item is products
and I have a vocabulary with the name products.

The vocabulary's terms list:

product-a
product-b
product-c

I used the module "taxonomy menu" to link the taxonomy to the path /products

My question is:
when I browse /products, the page of products views will appear,

but when I click product-a, or product-b or product-c, they do not link to products views.

How can I get products views when I click on a sub menu item?


texts: why the value of 'total paid' field on a completed order gets doubled?

texts:
I am using commerce 2 on Drupal 8. I need to get the value of a customer has paid on a completed order. But strangely the 'total paid' value gets doubled, here is output of dsm($order):

[total_price] => Array( [x-default] => Array
                     ([0] => Array(
                            [number] => 10.000000
                            [currency_code] => CAD)))

[total_paid] => Array([x-default] => Array
                        ([0] => Array(
                            [number] => 19.99
                            [currency_code] => CAD)))

The correct value should be 10.00 like 'total price', the 'total paid' should be the same. My purpose is to get the money value a customer has paid on order so I can update the value of another custom field. Isn't the 'total paid' field is the one I am looking for?


texts: iframe in - rewrite results - Override the output of this field with custom text

texts:
I'm trying to make a view for showing latest youtube videos in a block

I have a field called Youtube Video ID (Plain text) where I Drupal 8 stores the ID of the video...

I'm using the option of the field "Override the output of this field with custom text" in REWRITE RESULTS...

I'm doing something like this:

Like you can see.. I'm using that mark up to show a youtube video.. taking the value of the field....

the problem is that Drupal is cleaning the iframe mark up.. I think for security...

this is how Drupal render it in the website

When you configure the content type you can see a note:

Allowed HTML tags:   <big>
 <q>      <tt>

This field supports tokens.

how can I add more allowed tags?

How can I allow that HTML tag for this view?
¡Thanks!


texts: How to use different entity info per entity bundle?

texts:
I have three specific vocabularies that reside on different URIs and I need to have the Field UI configuration available for those URIs instead of only at one specific URI.

How could I configure this? The entity info is cached so alteration would not yeald the required result.

Bundle info only allows altering the label and some other unimportant value at this time.

This should basically act just like the entity uri override done by Forum module(although I think this is still not implemented yet).

Edit:
As I have mentioned I have three vocabularies A, B and C. I have three routes for each of those vocabularies and in there I am calling the Drupal\taxonomy\Form\OverviewTerms form with vocabulary argument which is the name of the vocabualry that I want to display.

This gives me the vocabulary term list overivew. Now I want to add the vocabualry edit form as local task on those paths which I still can do(manually).

The issue is that I would also like to have the Field UI(ie. manage fields, manage form display, manage display) available at those routes/paths. And this is problematic since the field ui route is defined in the vocabulary entity annotation and is universal for all vocabularies.

The only way I think I can do this is by somehow duplicating what \Drupal\field_ui\Plugin\Derivative\FieldUiLocalTask does but I was hoping for more simpler way by just having a different per-bundle information.

For more context/information see https://www.drupal.org/node/2460207


texts: How to do result biasing in Apache Solr by node rating?

texts:
I have a site with Drupal 7 with Apache Solr & rate module. In this site I have a content type that can be rated but search results are not being biased towards the better rated content.

If I go here: admin/config/search/apachesolr/env-solr/bias I found 3 kinds of biasing:

result biasing
type biasing
field biasing

None of these sections/tabs give me an option to bias the search results to the content that has a better rating.

I know I can relate a View with the search and order the content by rating, but that's not biasing exactly.

Any help would be appreciated. Thanks.


texts: Using views field formatter with paragraphs

texts:
I've got a question that is a worry to me. So what do I want to do?

I'm using drupal 8 with the paragraphs module. I want the content creators to be able to add an unlimited number of paragraphs that are presented as a grid view on the website.

For this I've created a paragraphs type called "panel" with a text and image field. I've also created a view of these paragraphs. So far so good. I can show all the panel paragraphs in a pleasant way.

I've then created a container paragraph called "panel_container" the only field of which is an unlimited number of "panel". So the idea is that the content creators add a new paragraph of type panel_container to a node and then create an unlimited number of "panel" paragraphs within this container paragraph. No comes the tricky part: How to show only those panels that belong to the respective panel_container paragraph.

For this I've installed the views field formatter module. This allowed me to choose Views as the field formatter for "panel" in "panel_container" and selecting the View I've created for the panel paragraphs type. Without any contextual filter this of course shows ALL "panel" paragraphs wherever a "panel_container" paragraph is inserted.

SO how do i show only those "panel"s that belong to the respective "panel_container"? I've selected entity ID for the views field formatter, which seems to hand over the entity ID of the respective "panel_container" to the view. Adding a "Paragraph: ID" contextual filter indeed restricts the result for the view to the "panel" that belongs to the "panel_container" which is pretty much what I want. The problem is that it shows the FIRST "panel" only eventhough several "panel"s where added to the "panel_container".

I've tried to fix that for some hours now but it appears that I'm simply not skilled enough... So does someone has a useful idea?

Thanks a lot in advance!


texts:
I have created views with BEF check boxes as a filter criteria.

I want to get count of each check boxes as mentioned in below image.

Reference link.

My view name is photo_search. So I have renamed below tpl to views-exposed-form--photo-search.tpl

  I have copied views-exposed-form.tpl from views/theme to
  mytheme/templates
  . But its not working (Cache cleared & Rescanned tpl from views).


texts:
I would like to optimize Views as they cause most of my performance bottlenecks.

The MySQL slowlog shows not only Views related query times > 5s but, what is more scary, selects with over 10 LEFT JOINs. I have already manually removed some columns from views. It was over 14 LEFT JOINs before...

Are there any solutions (without writing custom module queries) to eliminate or limit LEFT JOINs in Views select queries ?

I found there is the Shadow contrib module available. Is it ready for production website?


texts:
I have a site with a large number of taxonomy terms. Now I need to add meta keywords and meta description to all of this terms.
My solution is :

Resave all terms by VBO module.
Create a rules on "before saving taxonomy term".
The created rules execute a PHP code which adds meta keywords and meta description to each of the tags.

In this way when VBO is resaving terms one by one my rules is executed for each of theme and do the trick.

Now the problem is in step one. I have an "execute arbitrary PHP script" operation in VBO for terms. I use this code in it:

taxonomy_term_save($entity);

but I face this error:

  An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging
  information follows. Path: /backup-sar/batch?id=412&op=do StatusText:
  OK ResponseText: Fatal error: Function name must be a string in
  C:\xampp\htdocs\backup-sar\sites\all\modules\views_bulk_operations\actions\script.action.inc(20)
  : eval()'d code on line 1

This one with the same error does not work too:

taxonomy_term_load($entity->tid);
taxonomy_term_save($entity);

Any help would be appreciated. Thanks in advance.


texts: How to show/render 'Add to Cart' button?

texts:
I have a Commerce Kickstart 2 site.  I know how to create products and variations.  I used the Omega Kick Start theme and have implemented my own template files for the entire site.  Now I need to theme the shopping basket, starting with the "Add To Cart" button.  For the life of me - cannot get it right.

I've already tried the advice from this question -  but no luck.  For the record, my reference field is setup to render / display as Add to Cart form:

The Shopping cart block from Kickstart is enabled and set to my Content region:

The template file to render my product starts off like this:

<?php
$nodew = entity_metadata_wrapper('node', $node);

/* Manually extract the product ID to get a new wrapper */
$product_id = field_get_items('node', $node, 'field_product')[0]['product_id'];
$productw = entity_metadata_wrapper('commerce_product', $product_id);
?>

<?php echo $nodew->title_field->value(); ?>

<?php echo $nodew->body->value(); ?>

    <?php } $duration=$ nodew->field_duration->value(); if (!empty($duration)) { ?>

 Duration -
      <?php echo $duration; ?>

    <?php } $assignments=$ nodew->field_assessments->value(); if (!empty($assignments)) { ?>

 No of assignments -
      <?php echo $assignments; ?>

    <?php } ?>

What I would like to do is add/show the default, standard Commerce Kickstart "Add To Cart" button below all these attribute fields, and then hopefully I can use the standard commerce kick start shopping basket system (allowing me to just theme the relevant pages).

Just a side note - if I change the theme back to the Omega Kickstart 7.x-3.4 theme - my products show, and obviously the Add To Cart button as well, so I am fairly sure I did not break anything (uninstalled a module that was needed, or something like that).


texts: Save paragraph widget data in custom form

texts:
I am adding a node field widget in a custom form as described here and my code is:

$site_settings_node = Node::load($node_id);
$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')
  ->load('node.node_type.default');
if ($widget = $entity_form_display->getRenderer('field_my_field')) {
  $items = $site_settings_node->get('field_my_field');
  $items->filterEmptyItems();
  $form['#parents'] = array();
  $form['custom_form_field'] = $widget->form($items, $form, $form_state);
}

How do I update the paragraph field values in my submit handler? Is there something like the below that I can do?

$widget = $entity_form_display->getRenderer('field_my_field')
$widget->submit($items, $form, $form_state);


texts: Best way to add edit + flag links to a node being displayed inside Colorbox Node?

texts:
One of my content types opens in a colorbox node but I need an edit link and flags to appear for certain roles. I'm not using panels for this content type and I'm not using Display Suite either.

Blocks don't get displayed in a colorbox node so I'm wondering what's the easiest and most efficient way to add these links.

Php filter is fine to use.

Thanks


texts:
I am wondering if EntityFieldQuery is the proper way to do this

SELECT * FROM field_data_field_products JOIN node ON entity_id = nid

I'm wondering if there is a better way then my current db_query way, when dealing with entities.


texts: How do I create a search form with filters?

texts:
I have to create a searching form for a custom post type and I need it to have one search box and a couple of different (optional) search options in the form of select lists. I know I could have only the search text field and then expose the filters in the results page, but that's not what I'm looking for.

Is this possible? What modules/requirements would I need for something like this?


texts: Are use Drupal\Core\Form\FormStateInterface statements for a Drupal 8 hook required?

texts:
This may be obvious to expert D8 users, but; If I am implementing hook_form_alter in Drupal 8, the hook definition looks like this:

hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

In that there is a direct reference to FormStateInterface, so am I right in saying that it is redundant to also have the use statement in my file:

use Drupal\Core\Form\FormStateInterface; // Still works if I comment this out

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  ...
}

When generating the code using Drupal Console I get:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  ...
}

Best practice? It seems neater to me that the hook itself references FormStateInterface, making the use statement redundant.


texts:
I am using Drupal 7.43 and the Location module 7.x-3.7. Can a node have a 'wild card' ZIP Code that matches all ZIP codes?

Application:
Have a filterable view return a list of nodes with ZIPs within a given radius of a given ZIP code and also return all resources with a "wild card" ZIP.

Setup:
We have two node types: Resources and Organizations. Most have an address with a ZIP code associated with them. Some are tagged as "state-wide" or "national;' these do not have an address.

We have a page that lists all Resources and Orgs tagged with (for example) "Emergency Funding." There's an exposed filter on this page that lets visitors enter their ZIP code and a radius to filter down the results on the page. We figured out the logic to make the page return all statewide/national resources and all those within the given radius. But we wondered, "Can a node have a 'wild card' ZIP Code that matches all ZIP codes?"


texts: How do I inspect from a user's view how a given page element was created by Drupal?

texts:
I would like to be able to access a Drupal site as a given user/user-type (maybe using Masquerade) and from their view of the site be able to inspect how/where the page's configs/scripts/modules/nodes/etc were loaded from.

Background: It's possible in the next week I'll need to take over 10+ existing Drupal sites and most likely the maintenance for the sites will be driven by request like "On this page, I'd like to change this." While it's likely that I'll just have to use what I know of Drupal and hunt down where/how the given page elements are being created/managed, it would be nice to have the option to inspect how/where a given page element is being set within Drupal given a URL and the user that accessed it; think Firebug for Drupal.

If possible. it would be nice if this worked for 6 and 7, since the sites I believe are in 6, but will likely be ported to 7.


texts: How to check whether \Drupal\Core\Archiver\Zip::extract() succeeded?

texts: I called \Drupal\Core\Archiver\Zip::extract() to extract files from an archive. How can I tell whether extraction was successful?


texts: How can paragraph type's fields display in two different node fields?

texts:
There is a paragraph type 'paragraph01', it contains two fields: field_paragraph01_01 and field_paragraph01_02.

And a content type contains two node fields: field_01 (referenced paragraph01),field_02 (referenced paragraph01).

Is there possibility to achieve below?

Node field: field_01 just show field_paragraph01_01 both form mode and display mode, and node field: field_02 just show field_paragraph01_02 both form mode and display mode.


texts: How to show language switcher only on home page

texts: In my multilanguage site i am using Language switcher (User interface text) and I have it located in block called "Help". This block is shown in the middle of the site, where I want it. But I want it to be displayed only on homepage. I tried to hide by the restriction of a content type. But I wasn't successful.


texts: Why isn't the user #1 able to edit the user details?

texts:
I have one site in Drupal 6. When I log in as user #1, and I visit the page at user/[uid]/edit, I am not able to access this page. I get an access denied error.

Can any one please tell me what may be the problem, and the solution?


texts:
I have created a view block to display filter options. But in BEF settings I dont get check box options. Can anybody help me out.

Thank you in advance
embeeke


texts: Disable translation of watchdog messages

texts:
i have problem with drupal.
I'm using the watchdog function to save some log messages, but when i go to read them in the admin panel (admin/reports/dblog) they get detected by the T function and so i have a lot of unnecessary log entries inside the translate content page. Is there a way to disable the detection for that page?
Thanks


texts: how can i attach a taxonomy to the users profile?

texts:
I use drupal 7 and need to attach a certain taxonomy to a user. there is module for drupal 6 but as i see there is no module for that in drupal 7. how can i do that in my module by coding?

why do i have this question: i sell some digital files and now i am developing a module for selling my files. i want to sell them this way: each file has a certain taxonomy. when my user buys that file he or she gets that taxonomy. once he clicks on download link i have to check whether that user has that taxonomy already or not!


texts: Embed a specific checkbox matrix of taxonomy terms in a content type

texts:
I need design help for my website. I am trying to automate embedding a matrix (or webform) that lists taxonomy terms (url link) as rows and Categories as columns for each content in my custom content type. Matrix should be editable by the admin only. I want to use Views with contextual filter to view the matrix for each NID. A matrix will look something similar to below.

Taxonomy        | Category-1 | Category-2 | Category-3

Taxonomy-1      |   Checked  | Not Checked| Checked

Taxonomy-2      | Not Checked| Checked    | Checked

Taxonomy-3      |   Checked  | Not Checked| Not Checked

I tried the following design options but I don't know which one will be best:

1- Term level module: I found this module great but I don't have the option to use checkboxes instead of radio button. I can load the Matrix with taxonomy term with one click. I opened a ticket with the module maintainer but no response yet.

2- Slickgrid module: I am not sure if I can get what I want with Slickgrid but I am having difficulty in using the module and display data

3- Tablefield module: I was not able to load taxonomy terms. I thought it is not a convenient tool.

4- Matrix field module: Module is not maintained anymore, as far as I know

5- Webforms: I thought of creating webforms and use them as Entity reference to each node ID. But I am not sure how I can use Views to show the SUBMITTED webforms for each nid.

Thanks for reading this. Your help, ideas and suggestions are really appreciated :)


texts: Link checker modules fails to detect a test broken link

texts:
I downloaded, installed, enabled and configured the linkchecker module.  When I run it from the Drupal interface, it seems to be checking but I don't see in the report a test link (within ) that I have purposefully misspelled. This test link is to an external site.  Does it matter for the link checker module if my development site is not publicly accessible-- I think it is accessible only from campus.

Linkchecker version 6.x-2.7; drupal-6.26


texts: How can I link to a specific comment on drupal.org?

texts:
I'm aware that you can use [#1234] syntax in posts on drupal.org issue pages.

However, is there any syntax to point to the specific comment, like: [#1234:12]?

I was using it before, but I forgot the syntax and I can't find it anywhere.


texts: Multiple shopping cart view in cart page

texts:
I want to show shopping cart view in different style on mobile view .
how can I clone shopping cart view to show it on another format like unformatted list or what is your approach to show this views on mobile on none table format ?

Thank You


texts: How to set "Language Selector dropdown" required in node form

texts:
I want to know How to set "Language Selector Drop-Down " required in node form?

I tried to do this via hook_form_alter, but it seems $form['language'] is not created in this hook !

Is there any hook that let me modify language Drop-Down selector?


texts: Difference between #type and #theme in Render API

texts:
I am reading this theming article http://themery.com/dgd7/advanced-theming/render/manipulate and I have a question.

This article has the following code:

$page['highlighted']['new_stuff'] = array(
'#type' => 'container',
'#attributes' => array('class' => 'my-container'),
);
$page['highlighted']['new_stuff']['heading'] = array(
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => t('Heading'),
'#attributes' => array('id' => 'my-heading'),
);
$page['highlighted']['new_stuff']['list'] = array(
'#theme' => 'item_list',
'#items' => array(
  'First item',
  'Second item',
  'Third item',
),
);

I see that when you provide the #theme property you are telling the Render API to use the theme_item_list, and you pass it the #items variable. But isn't that exactly what you are doing when you set type to #html_tag, you're using the theme_html_tag and passing it variables?


texts: Image in View with Lightbox2 formatter lacking alternative text tag

texts:
I have a page view for image gallery. It has only 1 Photo field of Photo which has a field of type Image. In view it use "Lightbox2: lightshow: small-square -> large" as formatter. small-square is a custom image style.

The rendered page doesn't show any alt tag:

<img typeof="foaf:Image" src="http://www.example.com/sites/default/files/styles/small-square/public/6486388587_61846b6d84_1323732945.jpg" width="240" height="240">

I need to add alt tag to images. What do I have to change?

My drupal installation has these versions:

Drupal 7.10
Lightbox2 7.x-1.0-beta1
Views 7.x-3.0-rc3

looking at Lightbox2 modules's file lightbox2.formatter.inc it seems that alt tab should be forced to show, using image title.

  // Set up the title.
  $image_title = $item_data['description'];
  $image_title = (!empty($image_title) ? $image_title : $item_data['title']);
  $image_title = (!empty($image_title) ? $image_title : $item_data['alt']);
  if (empty($image_title) || variable_get('lightbox2_imagefield_use_node_title', FALSE)) {
    $node = node_load($node->nid);
    $image_title = $node->title;
  }

  $image_tag_title = '';
  if (!empty($item_data['title'])) {
    $image_tag_title = $item_data['title'];
  }

  // Enforce image alt.
  if (!empty($item_data['alt'])) {
    $image_tag_alt = $item_data['alt'];
  }
  elseif (!empty($image_title)) {
    $image_tag_alt = $image_title;
  }  $image_tag_alt = '';
  if (!empty($item_data['alt'])) {
    $image_tag_alt = $item_data['alt'];
  }
  elseif (!empty($image_title)) {
    $image_tag_alt = $image_title;
  }

So... where is the error?


texts: How do I add an active class for a views row?

texts:
I have a view block that lists different nodes. If I am viewing the block on any of those pages I'd like to add an .active class (or at least some kind of identifier) to highlight it with CSS as a form of active trail.
I have no clue on how to do this though, and I can't really find any useful documentation for this either.
Should I do this in a template, within views UI?
If i could get the current node ID views-view-fields--products--block-1.html.twig I could compare it to the individual row IDs i guess?
I've seen this patch, but I'd rather get a better understanding how I am supposed to achieve this myself than just adding a random patch.


texts:
According to the Drupal website (Drupal website), the following code should output a group of radio buttons:

$form['settings']['active'] = array(
     '#type' => 'radios',
     '#title' => $this->t('Poll status'),
     '#default_value' => 1,
     '#options' => array(0 => $this->t('Closed'), 1 => $this->t('Active')),
);

However, when i put this code into a function (in a bespoke module - in a class), placed in the Controller folder:

public function radioComponent ()
{

    $form['posting_settings']['comment_preview'] = array(

        '#type' => 'radios',

        '#title' => t('Preview comment'),

        '#default_value' => '1',

        '#options' => array(t('Optional'), t('Required')),

    );
    return $form;
}

I initially get an error stating:

  Notice: Undefined index: #title_display in Drupal\Core\Render\Element\Radios::preRenderCompositeFormElement() (line 20 of core\lib\Drupal\Core\Render\Element\CompositeFormElementTrait.php).

and

  Notice: Undefined index: #id in Drupal\Core\Render\Element\Radios::preRenderCompositeFormElement() (line 30 of core\lib\Drupal\Core\Render\Element\CompositeFormElementTrait.php).

But, even adding in those tags as follows doesn't produce radio buttons:

public function radioComponent ()
{

    $form['posting_settings']['comment_preview'] = array(

        '#type' => 'radios',

        '#title' => t('Preview comment'),

        '#default_value' => '1',

        '#options' => array(t('Optional'), t('Required')),

        '#id' => 'al1',

        '#title_display' =>'title',

    );
    return $form;
}

Does anyone know why the radios will not render as required?

Has anyone generated any code that would generate a radio button group?

  Is the issue that the radio component will only generate if placed in a form class - housed in the Form folder?  Rather than in a Controller folder.

Thanks.


texts:
How can I set the logo in my custom theme in Drupal 8?

I can see that Drupal looks for the logo.svg file. I have a PNG logo.png file that I used in Drupal 7 and I would like to re-use it. I cannot set the logo as a theme setting as in Drupal 7.

Is there a way through UI or custom code in the theme to set the logo?


texts: block['content'] contail both string and form

texts:
I created a form and used a block to show it. I would like to add a message before the form. Before I added "You can use the form below," the form was working fine. Right now, it doesn't work.

The code is the following one.

$block['content'] = 'You can use the form below';
$block['content'] .= 'Enter your email';
$block['content'] .= drupal_get_form('custom_request_price_form');

It just shows "Array" where it should show a form. Why does this happen?


texts: How do i generate token for each user they submit my custom form?

texts:
I have a created a custom module with simple form with only three fields ( Url, title & email ) , where user has to enter all the fields for submission.

I am able to send the mail to the user from my custom module but i need to create and attach a validation link (possibly with unique token for unique email) how do i generate a token so i can store it in database and use it for validating the user later.

(you may also help me with your own approach)


texts: "Article" html tag in body of Basic Page content type: what template is rendering this?

texts:
When creating a basic page, then previewing that page, here is a sample mark-up from the browser:

Name

iOS &amp; Android Developer

I had pasted the basic html ul/li/dl etc in the source code view using the ckeditor, saved then viewed the page in a browser.

Don't know why a
 tag was wrapped around content within established html tags but my main question is where to find what template that is adding the
 tag as well as the nested structure of the extra
 tags

I've looked in the template files within modules and Zen (my parent theme) but I haven't found anything yet. Where is the
 tag being generated? I think that would help me find the full mark-up.


texts: Ask user for URL on registration and create feed from the URL on his/her profile page

texts:
I know i should be using the Feeds module for this but i want to know how will i turn that particular URL into feed automatically when user enters his feed URL.

Basically i want to let users show their github activity feed on their drupal profiles.
URL for it is something like this https://github.com/githubusername.atom
So in a feed, the URL still remains standard and if i just ask them to enter their github username and generate the feed accordingly, that would be really amazing. I know how to do it in php but i don't know drupal moduling. It would be great if anyone could help me with it or give me ideas on how to do it.


texts:
Working on a migrate task for images. On d7 and d8 I've file_entity with two fields, but values are not imported.

Here is my source json:

{
  "items": [
    {
      "id": "2417",
      "uuid": "b0ad2fca-d100-45bf-9423-2474f00af68b",
      "filename": "terremoto_irpinia.jpg",
      "filepath": "public://terremoto_irpinia.jpg",
      "url": "http://localhost/sites/default/files/terremoto_irpinia.jpg",
      "links": [
        {
          "url": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-napoli-a-foggia-35-anni-dopo",
          "title": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-n...",
          "attributes": [],
          "html": false,
          "query": null,
          "fragment": null,
          "absolute": true,
          "display_url": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-n..."
        }
      ],
      "alt_text": "some text",
      "created": "1472139573",
      "stato": "Permanente",
      "created_year": "2016",
      "directory": "public://immagini/2016/terremoto_irpinia.jpg"
    },
]
}

On yml, this is my process:

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: http://localhost/modules/custom/migrando/files/download_immagini.json
  item_selector: items
  fields:
    -
      name: fid
      selector: id
    -
      name: filename
      selector: filename
    -
      name: uuid
      selector: uuid
    -
      name: filepath
      selector: directory
    -
      name: url
      selector: url
    -
      name: links
      selector: links
    -
      name: alt_text
      selector: alt_text

  ids:
    fid:
      type: string

process:
  uid:
    plugin: default_value
    default_value: 1
  filename: filename
  uuid: uuid
  status:
    plugin: default_value
    default_value: 1
  created: created
  alt: alt_text
  field_image_alt_text: alt_text
  field_fonte_immagine:
    plugin: iterator
    source: links
    process:
      uri: url
      title: title
      options: attributes
  uri:
    plugin: file_copy
    source:
      - url
      - filepath

Don't work field_image_alt_text and field_fonte_immagine fields.
What's wrong?

Thanks!


texts: Exclude certain webform field to be saved in Database

texts: Is there a way we can exclude certain webform field to be saved in Database. Don't want to exclude from email data.


texts: How to change order of taxonomy terms related to specific node field?

texts:
As in question. I have multivalued taxonomy field. Is this possible to control terms weight,  which are belongs to specific node field?

As a term weight, I mean weight inside single node. It's just a field value delta.


texts:
I have face this problem often in my drupal site. The drupal.js file is loading before jquery.js, so i get the "uncaught jQuery is not defined" error.

I have been using memcached also in my site.

But I can fix the error by the following steps

Restart memcached
Restart Apache
Cache clear
Run the cron

After doing the steps the jQuery is loading properly.

Now, i want to know the reason why the drupal.js loading before jquery.js?

FYI : This is happening, When I enable/disable any modules/features through UI


texts: Setting a Drupal.settings JS variable from a form field

texts:
i'm working on my first custom module and really fumbling along :). thanks in advance for your advice!

goal
i've added a checkbox to the comment form. if the user leaves it checked, then following comment insertion, i want to run some javascript on the following page.

possible approach?
i've added the checkbox using hook_form_alter:

function wt_comments_form_comment_form_alter(&$form, $form_state, $form_id) {

//show the checkbox
  $form['wt_comments_share'] = array(
    '#type' => 'checkbox',
    '#title' => t('Post this comment on your Facebook wall too. Spread the word!'),
    '#default_value' => 1
  );
}

this works fine. however, i'm struggling to pass the variable from php to js. i read up on adding variables to Drupal.settings using drupal_add_js(), but i don't have a solid understanding of basic concepts. this post seems to add values to Drupal.settings using #attached, but i couldn't figure out how to add the value of a normal form field.

i tried to run drupal_add_js() within hook_comment_presave or hook_comment_insert, to no avail:

function wt_comments_comment_insert($comment) {
  dpm( get_defined_vars() );

  //nothing
  drupal_add_js( array ("wt_comments" => $comment), 'setting');

  // nothing
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
}

So i added the variable to the global $_SESSION object:

function wt_comments_comment_presave($comment) {
  $_SESSION['wt_comments'] = $comment->wt_comments_share;
}

then, within a hook that does run drupal_add_js, i add the new session variable to drupal settings as described here:

function wt_comments_page_alter(&$page) {

  drupal_add_js("jQuery(document).ready(function () {

      if ( Drupal.settings.wt_comments.wt_comments == 1 ) {

        // dance around! jQuery('body').css('background-color','green');

      }

    });",
    'inline'
  );

  //reset session variable
  $_SESSION['wt_comments'] = '0';

}

note: i wonder if hook_page_alter is the best choice here...

is this the right approach? thanks again folks!
-ryan


texts:
I am using Field group module for creating fieldset in content type.

Can I have similar features while rearranging the fields selected in views.


texts: How do I force-indicate a vocabulary as a source for node breadcrumbs?

texts:
I have two vocabularies on my site, each node of certain content type has 2 term reference fields - one per vocabulary, single value only. For browsing through both vocabularies I am using Taxonomy Menu and Taxonomy Breadcrumb modules.

As long as I'm browsing through terms, the breadcrumb is ok, the problem starts when I step down to a node instance - the breadcrumb path is then always taken from vocabulary A, while what I want is the path from vocabulary B.

In the content type definition I checked vocabulary A as the source of active trail for menu (this is Taxonomy Menu setting most probably). Apparently that does not influence the breadcrumb. However, none of the options in the Taxonomy Breadcrumb config screen seems to have any impact on the source of the breadcrumbs.

What else should I check?


texts: How to bypass/skip payment after checkout in Ubercart?

texts:
I've tested Ubercart with Sagepay sandbox and it's very inconvenience to enter every time the payment. Another disadvantage is that when working on internal hosts, the redirection URL from external payment gateways never works, therefore when testing, payment is never completed.

How it's possible to bypass payment after checkout and make the order completed for testing purposes? Is there any option or module?


texts: How to create block to list all children of an entity?

texts:
I want to list all the nodes that have the currently viewed node as their parent.
To make this more tangible and less abstract, let's do an example:

I have a content type Locations which has an Entity Reference field called parent_location with an unlimited number of values.
For example:
- USA (3)                             [country level]
  - New York (4)                        [state level]
    - New York City (6)                   [city level]
      - Central Park (8)                    [landmark level]
      - Empire State Building (9)           [landmark level]
      - Times Square (10)                   [landmark level]
  - Illinois (5)                        [state level]
    - Chicago (7)                         [city level]
      - Sears Tower (11)                    [landmark level]
      - That bean looking thing (12)        [landmark level]

So when I view the content for USA (3), I wanna list all the children, meaning New York (4) and Illinois (5).
When I view New York City (6) I want to list Central Park (8), Empire State Building (9), and Times Square (10).
I want these to show up when I view /node/6 and be clickable, so that I can browse this nested child/parent structure.
It's already possible by default to traverse UP on the tree. Meaning I can easily get from Times Square (10) all the way up to USA (3).

However, I can't figure out how to list all children of the appropriate level!
I did create a block view called List Child Locations. And I've placed this view on the block Content. It shows up correctly, but it does not list the appropriate children.

When it comes to editing my view, I have no clue what I'm doing or how...
I see there's two options:
admin/structure/views/view/list_child_locations/edit/block_1
and
admin/structure/views/view/list_child_locations/edit/entity_reference_1
I think I have to do something with contextual filters, while I'm in the Entity Reference Display. But I can't find anything that looks like what I need...

Out of all those many options, which one do I chose to make sure it does something like
SELECT * from Locations WHERE parent_location = %current_location% ?
What's the right settings for my entity display to only list the children?


texts: Drupal Commerce product display text input on specific option

texts: I have a Product Display that shows a group of products with color and size options. However, I want to show "Custom" as a color option, and if the user selects it, I want a text box to appear where they can input custom text. I can do a custom submit hook to handle the input no problem, but is there a "Drupal way" to add a text box on a certain product option?


texts:
This is my problem:
I have 3 contextual filters, 2 Content : Has taxonomy term ID and 1 Content :Updated month

if I write in the url : test.com/International/North/06

It will show all the articles update the 06  in the International + North category

But if i write test.com/International/06 or International//06 to show just the articles update the 06 in the International category it doesn't work..

How can hide or set an empty condition on the second contextual filter to access on the third ?


texts:
I have the scheduler module installed, and i am using rules to notify users when new content is published.

The scheduler module is working perfect, i enter a future date and time for the content to be published. The content is published on the exact date and time.

Rules cannot action on this because there is no event coming with rules that allows me to perform some action when content is published, only when content is saved.

So my question is, how can i rules perform an action when content is published in a future date?

thanks in advance


texts: How to alter commerce order view access?

texts:
When viewing an order, I want to do checks per order, whether the user may view that order or not.

function my_commerce_entity_info_alter(&$entity_info) {
  $entity_info['commerce_order']['access callback'] = '_my_commerce_commerce_order_access';
}

function _my_commerce_commerce_order_access($op, $entity = NULL, $account = NULL) {
  return $entity->id == 99; // just for example
}

The above did not work.

I didnt find anything like entity_access_alter or similar.

What do I do wrong?


texts:
I've installed the Ajaxblocks Module (see https://www.drupal.org/project/ajaxblocks). I have 2 blocks to be loaded by ajax.

The AJAX request looks like this:

mywebsite.com/ajaxblocks?blocks=block1/block2

The success function looks like this:

success: function (data) {
  // Replaces the placeholder divs by the actual block contents returned by the AJAX call,
  // executes the extra JavaScript code and attach behaviours if the apply to the blocks.
  Drupal.freezeHeight();
  for (var id in data) {
      console.log("Worked");
    Drupal.ajaxblocksSetBlockContent(id, data[id]);
  }
  Drupal.unfreezeHeight();
}

And the returned json looks like this:

{"block1":{"content":"my block content","ajaxblocks_settings":""},"block2":{"content":"my second block content","ajaxblocks_settings":""}}

Now only the first block is loaded. Why is this? The for-loop doesn't seem to work properly


texts: Executing JS calls during user login validation (Drupal 7)

texts:
I need to execute three different JS calls during the login process (for tracking reasons) depending on how the validation goes. I have no idea where to include them:

1. Event: Login failed (wrong password and/or user name)
-> wrong_pass();

2. Event: Incorrect E-Mail format (I am using E-Mail addresses as user names)
-> wrong_email();

3. Event: Login successful
-> login_ok();

How can I catch these events and react to them by executing the respective JS calls?

Thanks in advance!


texts:
I want to build a view sorting it on the basis of the term field. I need to show the term as a title in each group, like this:

Term 1:

node1
node2

Term 2:

node3
node4

Term 3:
...

How can I achieve this?


texts: How to compare 2 row fields in a view and don't display them if some conditions are verified?

texts:
I have a view table with 12 Fields & 10 Rows and I wish to compare two known fields with defined field names and check if both fields are:

If data partially matches (Field 1 with Field 2 or vice versa) then display rows, e.g.:

Field 1: Apples, Oranges.
Field 2: Oranges, Grapes.

If none matches then don't display either of the two rows.
If row data is blank for one of the fields then don't display them.


texts: Get the ID that for the node that has been just created

texts:
I am trying to get the node ID that I have just created. If I do the following code from this answer.

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

I implemented hook_ENTITY_TYPE_view() (just to test the code), but it gets the ID for all the nodes, while I want the ID of the node that has been created to modify a field value for that node. Is this possible?

Should I use the code I shown in a hook_form_alter() implementation or maybe inside a form submission handler?


texts: How to use a contextual filter argument (term ID) in a View page title?

texts:
This question asks how to use a Views contextual filter argument as the title when using a Taxonomy Term: Name filter.
My question is how to set the name of a view page to a contextual filter argument when using a Content: Has taxonomy term ID filter.
My View looks like this.
Show Taxonomy terms of type Group (my custom vocabulary)
Type: Page
Path: /groups/%
Contextual filter:

(field_ref_term_group) Content: Has taxonomy term ID
When the filter value is NOT in the URL: Show "Page not found"
When the filter value IS in the URL: Specify validation criteria (Taxonomy term ID)

Relationships: Relate each Content with a field_ref_term_group set to the taxonomy term., required
Fields: Taxonomy term: Name [hiddden], Link to the Taxonomy term is unchecked
View settings screenshot:

I then set the View title to {{ name }}. After saving and clearing the cache and navigating to the view path (/groups/4), then I see the page title (the <title> tag) as {{ name }} instead of the name of term 4.
How can I print the actual term name as the View title when using a Content: Has taxonomy term ID relationship?


texts: Printer - PDF format: How can I change the header info and add page count on the footer?

texts:
I like this Printer module on my Drupal 7 site. But, when it generates PDF, it contained breadcrumb and no page-count on the footer. Is there a way to add name of "Content type" and node "Title", instead of breadcrumb? I also would like to have the page-count number on the footer on every page. Is there a file that I can modify?

PS: I'm using mPDF third-party tool


texts: Add a span and class to menu items that has children

texts:
I'm customizing the main menu using the Menu Block Module. I need to set a class for all li elements that has children regardless of level. I might need to add a span inside the a-tags as well. Is it possible to do this in the template.php or do I need to alter module files. I would preffere not to edit module files if possible.

Like:

   Menu item name

Is this doable with some:

function theme_menu_link(array $variables) { ...?... }

[edit]

Menu items with no children has the class="leaf". It should be possible to style the menu items li (has children) and then cancel the rule-set for the class li.leaf (has no children). The span can be added by using some li::after rule-set and removed with eg li.leaf::after {display:none;}

In this way it can be solved with CSS only. The problem is I need to use the   for a click event. So at least I need a real span inside the li a witch is not a "leaf".

Anyone who can help me with a theme functions for this?


texts: How to get field value from referenced entity inside a field collection

texts:
My structure is as follows:

I've got a custom contenttype with a multivalue field containing a field_collection. In this field_collection there are an amount field, a entity_reference_field and a computed_field. The referenced entity also contains several fields.

What I need to do:

Step 1:
In the computed field (inside the collection) I need to get the value of a certain field of the entity, referenced by the entity_reference field (also inside the field collection) and multiply this value with the value of the amount field.
Step 2:
In another computed field (on the node itself) I need to sum up all the values of all the computed fields inside these collections.

My Problem is primarily Step 1


texts: How to grant permission to specifc role to perform CRUD operations on a particular content type only?

texts:
I've set up different roles and in my site and I want a specifc role to grant permission to perform CRUD(create, Read, Update, Delete) operations on a particular content type only. But I can't find any such option in drupal admin.

Any suggestions?


texts: Multiple url aliasses per node in multi language website

texts:
Hope this is the right place for this question. I'm turning to you guys because I just cannot decide on the best way to go for this issue.

I'm currently developing a multi-language site which is split up in 2 main sections. Section A will be the main section and is available in 2 languages; Dutch and English. Section B will only be available in English.

Section B will have a different Menu, a slightly modified layout and some other blocks will be shown on different pages within the section.

I'd like to achieve the following url structure:

Section A:

/nl/title-of-a-node-in-dutch

/en/title-of-a-node-in-english

Section B:

/en/section-b/title-of-a-node-in-english (If possible, I'd like to drop the language prefix /en/ here)

I've configured Drupal with Entity Translation (+ Title module), so each node has translations on field-level and is not entirely duplicated like it would be the case with Content Translation (i18n).

The problem is that I'm going to have a lot of content (tens of thousands of nodes) for this site and some items should be shown in both Section A and B.
Content that will be shared with both sections should only exist in one node. I definitely do not want to create an extra node with the same content just to make it available for Section B, this would be bad for content management and have a huge impact on the database.

Some of the solutions I've thought of:

Create 2 checkbox fields in the content type to indicate in which section the node should be made available. Create a hook on node insert/update and check which section was selected. If Section B was chosen, create an extra url alias which starts with /section-b/{node-title}. This would make the node content available via this extra alias, but I'm not sure what the implications this method will have, like how to handle breadcrumbs or (multilingual) Menu Structures for Section B
Configure Drupal to use a language fallback with Language Neutral and somehow add Section B as a custom language with the prefix 'section-b'. (is this even possible?)
Use url rewrites /section-b/my-title -> /en/my-title and programatically load the node and show the content via theming/templates
Maybe I can do something with Rules?

Relevant modules I'm using:
pathauto, entity_translation, path_translation, i18n_translation, title

Do you guys have any other suggestions in how to set this up? I hope I'm clear on this issue. Content management is very important in this matter :)

Thnx!


texts: How do you add "Rating Field" to a content type?

texts:
I know that there are many rating or voting module like:

Fivestar
Rate
Star

etc for drupal 7, I haven't found any modules for Drupal 8. How can I create a simple 5 star rating widget in Drupal 8?

Ideally I would like a solution, that doesn't require much coding, but can be achieved using existing modules and configuration.


texts:
how to validate file upload in drupal
means,

in my form allowed only txt file, but now user also can upload image file also after change the extention .jpg -> .txt

function oz_workbench_moderation_buttons_form_alter(&$form, $form_state, $form_id) {
  dpm($form);
  if ($form_id == 'catalog_node_form'  )
    {
    $form['#validate'][] = 'upload_validate_function';
       return $form;
    }
}

function upload_validate_function(&$form, $form_state){
$extensions = array('txt' => 'text/plain; charset=us-ascii','doc' => 'application/msword; charset=binary','pdf' => 'application/pdf; charset=binary','xls' => 'application/octet-stream; charset=binary','docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=binary');
$uploadedfile=count($form_state['values']['field_application_document']['und']);
        for($i=0;$i<$uploadedfile-1;$i++){
                $file_name=$form_state['values']['field_application_document']['und'][$i]['fid'];
                $file_handler = file_load($file_name);
                $file = $file_handler->uri;
                $filename = $file_handler->filename;
                //echo $file;
                $finfo = new finfo(FILEINFO_MIME);
                $type = $finfo->file($file);
                //echo $type;
                    if (!in_array($type, $extensions) )
                    {
                    drupal_set_message(t($filename.' is not valid file'), 'error');
                    }
         }
}


texts: Adding checkbox to select records in a view

texts:
I have a list of students and I have added a custom handler to add checkboxes against each student to mark as present. When I use filter, I loose the state of checkbox and I have to use filters because I have many students in the list and are on many pages. Same happen when I move to the next page. How can I retain the state of checked text boxes.

Thanks in advance.


texts: Video file upload errors with Cloud FIles

texts:
I'm using the CloudFiles module to host my uploaded files on Rackspace Cloud Files. This is working very well for all of the photos I'm uploading, but it seems to be failing when I upload videos.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
'rcf://videos' for key 'PRIMARY': INSERT INTO {cloud_files} (uri, filemime, filesize)
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2);
Array ( [:db_insert_placeholder_0] => rcf://videos [:db_insert_placeholder_1] =>
application/directory [:db_insert_placeholder_2] => 1 ) in drupal_write_record()
(line 7013 of /var/www/vhosts/mydomain.com/includes/common.inc).

I'm not sure, but it appears that when the process finally gets to the CloudFiles module and the CF module is trying to insert that into the database, the filename appears to only be "rcf://videos" when it should be something more like "rcf://videos/original/my_test_video.mp4" (I'm guessing).

But perhaps this is the wrong understanding of what I'm seeing. It appears that there is a directory entry in the cloud_files db table, so perhaps the module is trying to insert entries for the intervening directories and it's accidentally trying to insert it twice or something... I don't know. I'm confused.

I'm not a drupal wizard (yet!) so I'm having real problems tracing this error down to its source. I'm assuming the issue is in the Video module since the CloudFiles module is working for image uploads.

Can you help me track down where the filename is set and/or converted?


texts: Drupal's .htaccess does not deny access to nodes

texts:
D7, .htaccess woes. I'm trying to deal with referer spam in my Statistics module and block the most notorious referers. I edited my .htaccess file like this:

# Follow symbolic links in this directory.
Options +FollowSymLinks

# ... some options ....

# Various rewrite rules.
<IfModule mod_rewrite.c>
    RewriteEngine on

    # ... some more options ....

    # Block referer spam
    RewriteCond %{HTTP_REFERER} spamhost1\.com [NC,OR]
    RewriteCond %{HTTP_REFERER} spamhost2\.com
    RewriteRule .* - [F]
</IfModule>

When I went on to test this setup, I found out that it works correctly only if I try to access my site's main page. This request results in a correct 403 response:

GET http://www.example.com/ HTTP/1.1
referer: http://spamhost1.com/
Host: www.example.com

But any request to a node page produces 200 OK and loads the page which I'm trying to block:

GET http://www.example.com/node/1 HTTP/1.1
referer: http://spamhost1.com/
Host: www.example.com

Is it a matter of the Apache configuration in my server? How do I deny access to node pages?


texts: Add Additional (Term Reference) Field to repeating Date & Time Field for Locations

texts:
So I have a question that I am not quite sure how to handle in Drupal. (I come from a Wordpress background).

So I have an Event Content Type.
In this event CT I have a repeating Date/time field and I need each date/time field to be connected to its own Location. (All locations are stored in a Taxonomy called "Venues")

For Example, I could have 3 events on June 6th. Each at separate times but all three at different locations. So rather than create 3 Event nodes. I just want to set the three times and dates in one node.

Any idea's how to go about this? I was thinking I could do some type of field attach but I am not quite sure if that would be the way to go about it or to even start.


texts: Is there any module for Drupal 8 that will do same functionality as nodeblock does, or do we have to programmatically render it?


texts: Programmatically change select field options in contact form

texts:
I'm currently rendering a contact form programmatically in a block plugin like so.

    $type = 'contact_message';
    $bundle = 'my_contact_form_name';
    $values = array();
    if (\Drupal::entityManager()->getDefinition($type)->hasKey('bundle')) {
        $bundle_key = \Drupal::entityManager()->getDefinition($type)->getKey('bundle');
        $values     = array($bundle_key => $bundle);
    }
    $entity = \Drupal::entityManager()
        ->getStorage($type)
        ->create($values);

    if ($entity instanceof EntityOwnerInterface) {
        $entity->setOwnerId(\Drupal::currentUser()->id());
    }

    $form = \Drupal::entityManager()
        ->getFormObject($type, 'default')
        ->setEntity($entity);

    $my_rendered_form = \Drupal::formBuilder()->getForm($form);
        $content[] = [
            '#type'    => 'html_tag',
            '#tag'     => 'h1',
            '#value'   => 'My Form Title',
            'form'    => $my_rendered_form,
        ];

It grabs and renders the form just fine. But the form has a select field and I want to alter the options for it. This is because the options should be dynamically generated based off the values of certain nodes. I already have a field called 'my_select_field' but I'm not sure how to change the values from it. When using die(print_r($my_rendered_form['my_select_field'])); I receive a very large array and the my_select_field, and the test data I put in it appears in many locations in the array.
My ultimate goal would be to accomplish something like this

$form['my_select_field']['#options'] = [
    1 => 'My new option 1',
    2 => 'My new option 2',
    3 => 'My new option 3',
];

How would I alter the options in a select field in a programmatically rendered contact form?

UPDATE: I found '#options' in the array

        [#options] => Array
            (
                [test1] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 1
                    )

                [test2] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 2
                    )

                [test3] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 3
                    )

                [test4] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 4
                    )

            )

But the options are objects rather than strings I can edit. I should probably also mention that the select field I have is set to multiple checkboxes.

EDIT: I'm willing to use a form alter hook if that is necessary. But if that's the case the same question applies.

UPDATE 2:
I attempted altering the form using the hook form alter method like so

        $form['my_select_field']['widget']['#options'] = [
            1 => 'New option 1',
            2 => 'New option 2',
        ];

And the new options do appear, but now when I submit the form I receive the error

  The value you selected is not a valid choice.


texts: How to use Rules to send an eMail with a body containing all items of a field collection?

texts:
I've defined a content type that contains a field collection. The field collection contains 4 fields. When the content is created, it may have one or more of the field collections.

I set up a rule to send the email to users of a specific role.  I've used tokens in the rule to specify some data fields in the body. I'm currently stumbling on how to specify the one or more field collection fields in the body of the email.

I found some posts that indicated that I needed to add a condition for "node has field" which I have done. I wasn't sure what to select from the drop down lists, so, I took a logical guess. That seemed to provide some more tokens.

However, I've tried several different methods to specify the field collection in the body of the email, but, all have failed. The email is empty in the spot where I tried to display the field collection.

How can I specify the fields of a field collection in the body of an email?


texts: How to update route cache when saving an entity?

texts:
I have added a custom access check to the /user/{user} route:

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.user.canonical')) {
      $route->setRequirement('_profile_access', '\Drupal\mymodule\Access\ProfileAccessCheck::access');
    }
  }

}

with some starter checks:

/**
 * Determines access to user profile based on conditions.
 */
class ProfileAccessCheck implements AccessInterface {

  /**
   * Checks if this profile is publicly visible.
   *
   * @param \Drupal\Core\Routing\RouteMatch $routeMatch
   * @return \Drupal\Core\Access\AccessResultAllowed|\Drupal\Core\Access\AccessResultForbidden
   */
  public function access(RouteMatch $routeMatch) {
    $requested_profile = $routeMatch->getParameter('user');
    $show_profile = (bool) $requested_profile->field_show_profile->value;

    if ($show_profile === TRUE) {
      return AccessResult::allowed();
    }

    return AccessResult::forbidden();
  }

}

This appears to work fine, although it seems that the "View" tab does not hide/show in the admin when saving a user. If I clear the site cache, the tab is there on a user edit (or not, depending on value). Is there a way to get it to bind to the user or is it not worth while?


texts: Is it possible to add to different aliases to the same table in a dynamic query?

texts:
I would like to use a example query for retrieving a full tree of the nested set model in a dynamic query.

SELECT node.name
FROM nested_category AS node,
        nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;

The problem is that dynamic queries can't alias the same table. Is there a work around for this?


texts: Restrict admin to search specific content types

texts:
1.Using search configuration module I have restricted the user role to search particular content type, this worked for me. But when I tried to apply the same approach to administrator this did work. I have unchecked the Admin bypass (primary user with id 1) the option too.

Is there a way to restrict the admin too to search specific content ?

2.And my second issue is about pagination, using the same module pagination is successfully applied, but for admin it is default set to 10 items per page, can I alter this?


texts: Saving custom fields for nodes and users

texts:
I'm trying add a new user to drupal 7, here is my code:

$values = array('name' => $name, 'pass' => $password,  'mail' => $email, 'status'=>1);
$newUser = user_save('', $values);

But i also have the new field field_foobar, if i add it to the values array drupal does nothing with it. What is the correct drupal way of adding these values to my user object so that drupal saves them when i call the user_save function?

I also saw that the fields are stored in the same type of table that stores custom fields of nodes. Also can't get this done, but i guess these 2 problems can have the same solution.

Thanks!


texts: How can i include views page in search results

texts: I had created a view called "donor" with a page display. I includes nodes from content type "Donor-node". The title of "donor" views page is "donor wall". I created a view with type as content, which lists all nodes. An exposed search form with search term field. Is there any way to include "donor wall" page in this search results. If any one search for a key word donor, donor wall needs to list in result.