texts: Why do I get an error about the modules/custom directory not existing?

texts:
I have installed Drupal 8 on Ubuntu. All works well, but I cannot create a new module using Drupal Console.

When I run drupal generate:module, I get the following error message.

  [InvalidArgumentException]
  Module path "/var/www/html/maryem/modules/custom" is invalid. You need to provide a valid path.

Why? How can I avoid that error message?


texts: Display Ubercart sell price in Apache Solr search results

texts: I manage an ubercart store that is indexed by Apache Solr. The search indexes the sell price and it's one of the facets. However, the price is nowhere in search-result.tpl.php. It's also not available in the search results preprocess hook in template.php. Is there somewhere else I can inject it into the search results without performing a separate database query for each search result.


texts: Accessing user's custom field in html.tpl.php

texts:
In my html.tpl.php , I was printing this:

    print $user->name;

which displayed username.

But now I need to print Custom field "First Name" instead of username.

So I tried this:

   print $user->field_first_name[und][0]['value'];

which is not printing anything  although the field "First Name" has some value.

Where am I going wrong ? Am I missing some obvious thing ?

Thank you .


texts: Display multiple values in entity reference view

texts:
I have created an entity reference view to display the values of a multi value field in Drupal 8.

The field is a date field.

In the view I have set the "Multiple Field Settings" so the date field values will be shown in separate rows.

When I preview the view, I can all of the date values shown is separate rows as expected.

I then create an entity reference field and select the view as its reference type /view.

The problem is, when I then view this field, I am only shown a single value instead of all the dates as seperate rows.

How do I setup a multi value field so I can select from all of its values in an entity reference field?

Thanks in advance.


texts:
I tried webform validation, I can validate textfield component for numeric value.
However, I cannot find how to set it as integer value only.
How can I validate numeric (integer) value.


texts:
I have a theme and am loading CSS in the traditional way, through the theme.info file, as follows:

stylesheets[all][] = css/style.min.css

However, my clients site uses HTTPS. And every 3rd or 4th load for some reason Drupal tries to load all my files via HTTP rather than HTTPS, causing all the stylesheets/js/images not to load.

Is there any way to force Drupal to use HTTPS on assets while maintaining using the theme.info file to load them?


texts: Remember View results on a browser back button click

texts:
I have a view with some exposed filters that show some links. When I select a filter option, an ajax search is done and it shows the results. I click in one link and then I click in the browswer back button to go back to the view page.

Now, all results are shown and not the filter option ones.

How can I get that the view remembers the ajax search?


texts: Passing parameters from Panel to View (contextual filter)

texts:
I ran into a little problem today, I have a specific panel for all my products.
This panel contains out of a 3 column layout.

One of those columns contains a list of all other products in the same category. (which is a view).

When I created the view, I added a contextual filter to only display products out of the category that was send. (Categories are nodes and linked by a node reference) (This is just to allow the client to easily add and remove categories so he doesn't have to use the build in taxonomy)

I noticed however that I can only use the node id of the category to filter.

The problem is that the Panel only sends the string to the View, so the filter doesn't work.
Is there a way to get the node id of the linked category?


texts:
I'm trying to create a controller within my custom module, but the controller still doesn't response when visiting the associated path.

Here are my files:

my_module/my_module.routing.yml:

my_module.agreement:
  path: 'my_module/send_consent'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleController::check_agreement'
    _title: 'Agreement controller'
  methods:  [GET]

my_module/src/Controller/MyModuleController.php :

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

    public function check_agreement() {
        die('hello from controller');
    }
}

To test I visit myproject.local/my_module/send_consent

Any help?


texts: Views module doesn't call hook_node_view() when set to display fields

texts:
I use Drupal 7 with Views and want to override some node field output in a view (namely change its Title to something I want). To accomplish that I set the view to display Fields and not Context or Rendered Entity and select Title and Body from the list of fields. And here is where the problem lies:

I have a (homemade) module that makes use of hook_node_view() hook to modify Body and Teaser text. When I display article body as a Field in the Views this hook for some strange reason is not called (on Context and Rendered Entity all works correctly). So I need a way to either:

override Title output while NOT setting my view to display Fields, or
find a way to call hook_node_view() while setting my view to display Fields.

Is there a way to do it?

Upd: provided a screenshot showing that hook_node_view() is not called on teaser when setting Show to Fields (left pane) but called when setting Show to Content (right pane):

screenshot showing that hook_node_view is called on teaser when setting Show to Content and is not called when setting Show to Fields http://ari-linn.nightmail.ru/views_and_hook_node_view.jpg

Upd 2: Okay, I did some Drupal colonoscopy and it even works though I can't say whether it is the right way to do things (probably not). I found out that when you render context Drupal apparently thinks you want to render a normal node but when you render fields Drupal is at a loss and doesn't think you're dealing with nodes anymore. Thus it doesn't fire any node hooks including hook_node_view(). If anyone still needs to run their functionality of hook_node_view($node, $view_mode, $langcode) they can use hook_views_pre_render(&$view) though access to node $view_mode and $langcode will be gone.

In case people out there are interested how I override node titles in taxonomy views, here is the scenario. My task was to override node Title with the value of another field, SortKey, and do it only in taxonomy views. I'm happy with "Britney Spears" node title at the main page but when it comes to taxonomy I want her to display "Spears, Britney".

I personally thought it to be tiresome and bothersome to deal with fields (they mess up all my CSS) and found a hack in Views 7.x-3.3: if you set Show parameter in your view to Fields and select Material:Rendered Material AND any other field (you can exclude it from display, just make sure Rendered Material is not the only field you load) you'll get a neat and tidy Node object at $view->result->_field_data. I fail to explain how it is so but it's there, and you can bend it to your needs, and what is even better Drupal will think you're rendering a node and fire all node hooks on it. I pray though that Views coders won't remove this wonderful hack in later versions ruining my code.

Here is the code:

/*
* Changes MYARTICLETYPE title to sortkey on taxonomy views pre-render
*/
function MYMODULE_views_pre_render(&$view)
{
    if($view->name == 'taxonomy_term')
    {
        foreach($view->result as $i => $value)
        {
            $node = &$value->_field_data['nid']['entity']; //it's a real node, yes.
            if($node->type == 'MYARTICLETYPE') //override titles only for this type
            {
                $node->title = $node->field_sort_key['und'][0]['value'];
            }
        }
    }
}


texts: wysiwyg + ckeditor - failed to open stream sites/default/files/js/wysiwyg/wysiwyg_ckeditor_XXX.js

texts:
I am using WYSiWYG with CK editor. I am getting this error whenever i am trying to access a form with ckeditor.

  file_get_contents(MYSITE/sites/default/files/js/wysiwyg/wysiwyg_ckeditor_lMF9rzHK588_LcHaW11FHc_RkSCpdKrS7MgWsyqXXEM.js)

  [function.file-get-contents]: failed to open stream: HTTP request
  failed!

  HTTP/1.1 404 Not Found in drupal_build_js_cache() (line 4846 of
  /var/www/html/dev3/wifh/includes/common.inc).

This file "wysiwyg_ckeditor_lMF9rzHK588_LcHaW11FHc_RkSCpdKrS7MgWsyqXXEM.js" exist with content

window.CKEDITOR_BASEPATH = '/MYSITE/sites/all/libraries/ckeditor/';


texts: Deleting a Drupal 8 Content Type Field also Deletes all the Views linked to it... Undo?

texts: So I deleted a Drupal 8 content type field and it also deleted the views that is associated with it. Is there an undo button?


texts: Feeds importing unique nodes over and over

texts:
I'm trying to import events to a calendar from an external ics..
I installed the Calendar module with the Feeds module. Unfortunately it creates the whole time new nodes. Even if the UID is unique (mapped to field field_gimme_uid) in the node. Update nodes is setted 'on'. I have checked everything but everything seems alright. The unique field is correctly imported (and the same for multiple nodes)..

I have a contenttype "Evenement" with the following fields:

Evenement (title)
Datum (field_event_date) Date
Gimme-UID (field_gimme_uid) Text

I have a feed that maps the ics import to the nodes

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'ics_importer';
$feeds_importer->config = array(
  'name' => 'Gimme Agenda',
  'description' => 'Gimme agenda importeren van het account website',
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => 0,
      'use_pubsubhubbub' => 0,
      'designated_hub' => '',
      'request_timeout' => '',
      'auto_scheme' => '',
      'accept_invalid_cert' => 0,
      'cache_http_result' => 1,
    ),
  ),
  'parser' => array(
    'plugin_key' => 'DateiCalFeedsParser',
    'config' => array(
      'indefinite_count' => '52',
      'indefinite_message_display' => TRUE,
      'until_not_utc' => FALSE,
      'skip_days' => NULL,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => '1',
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'SUMMARY',
          'target' => 'title',
          'unique' => 0,
          'language' => 'und',
        ),
        1 => array(
          'source' => 'DTSTART',
          'target' => 'field_event_date:start',
          'unique' => FALSE,
          'language' => 'und',
        ),
        2 => array(
          'source' => 'DTEND',
          'target' => 'field_event_date:end',
          'unique' => FALSE,
          'language' => 'und',
        ),
        3 => array(
          'source' => 'UID',
          'target' => 'field_gimme_uid',
          'unique' => TRUE,
          'language' => 'und',
        ),
      ),
      'insert_new' => '1',
      'update_existing' => '1',
      'update_non_existent' => 'skip',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'evenement',
      'language' => 'und',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => '900',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 1,
);

My modules:

Drupal 7.56
Calendar module 7.x-3.5
Date 7.x-2.10
Date iCal 7.x-3.9
Feeds 7.x-2.0-beta4

My ICS that I use to import can you find here

Why is it importing the whole time the same nodes?


texts: Creating a rule to display Terms Of Service upon Ubercart checkout

texts:
I have a small web store running Ubercart and with one of the items I must display a terms of service agreement. I have it displayed upon checkout as a requirement to proceed. Some of my other items do not need this service agreement to be purchased.

Question: Is it possible to set up a rule to display the Terms Of Service up check when only certain items are in the cart?


texts: Same module for different Drupal versions

texts:
I've just started developing Drupal module and have completed the simple "Hello "World" module. The module is working fine on both Drupal 6 and 7.

How can I use the same module on both Drupal 6 and 7, instead of packaging it as 2 separate modules?


texts: Version control on Entity form type submissions

texts:
A project collecting data from multiple entity forms was handed over to me. My client requested the implementation of a review mechanism for the data that are stored in entity form submissions.

The reviewers should have the ability to edit the submissions while they are keeping the initial content intact. The features extend to comparison between the various versions of the submission along with comments that can be attached to each version explaining the scope of the changes.

Pretty much the exact functionality that Node revisions are covering at the moment.

Unfortunately I just discovered that revisions are not available for entityform submissions (Add revision support to submissions) leading me to a dead end.

So, I seek some experienced guidance if there is a workaround to this, that I'm unable to see.

Could I create this versioning system somehow with the current data
structure?
Would it be able to migrate the data collected from form submissions to content type nodes so that I can use their revision framework (along with Diff and Node Compare modules)?


texts: Programatic output of views block breaks jquery

texts:
I am using the following code to load a views slideshow block:

  <?php
            $view       =   'pagetopimage';
            $block_id   =   'block_1';
            $args       =   array(32);
            print views_embed_view( $view, $block_id, $args );
        ?>

The block is produced just fine but the javascript that makes the slideshow work is abscent.

 Can you enlighten me about a way to programmatically load the block whilst maintaining the javascript functionality, please?


texts: Client needs Ubercart member sign up function, but there is error with edit/option_prices

texts:
I have a Drupal 7 client with Ubercart installed. They would like to add a Membership feature to their site where the members can receive a discount on their products and services.

We have Ubercart Price Per Role installed (in spite of it not being updated since 2013 which makes me nervous), which has added a nice little Member Price field in Product. I have added a test Product Class called Memberships to allow for membership levels.

I understand that a Role can be assigned to a Product Class through Attributes and Options to allow for membership expiration dates. Attributes and options have worked just fine for other products, but when I clicked the link for 'Note: "Price" column is the default option price. To set option prices per role use the options prices form.' 'I get The requested page "/?q=node/test/edit/option_prices" could not be found.'

Now it is entirely possible that I am trying to do it all wrong and that fixing that error won't get me the solution I'm looking for.   So, I would also like to hear hetherw I just headed down a rabbit hole, as well as finding out why the edit page cannot load.


texts: How to change webform default email address from sender side?

texts:
I'm using webform module, when somebody submits the form mails will go from address which we mentioned in the custom field, this works fine.

But instead of adding in custom field, I want to change the default from email address. Is there any way to do this?

For reference follow this image:


texts: I added a new module and it breaks Javascript from my theme. How can I fix?

texts:
I have recently installed a new module, "Views Nivo Slider", and it is breaking the javascript on my web site that I have added via my theme.  I'm at a loss as to what I should do to fix the issue.

By Break, I mean that the code from my theme no longer executes. It also throws no errors. It just acts like the code no longer exists

In my custom theme, I add javascript by adding this line in the theme:

scripts[] = js/js.js

I had added the code by using the onready event:

$(document).ready(function() {

Now I read online that perhaps this was not the best method to add code and that I should bind with drupal events. I tried to change my code to use this method to see if it would make a difference:

Drupal.behaviors.addMenu = function (context) {

My code always works IF this module is not being used.  However, whenever I turn this module on, it breaks all of my javascript. I've spent about 2 hours looking around and searching for articles and I have had no luck so far.

The articles I was looking at to learn more about behaviors were:

http://www.phase2technology.com/node/663/

http://mydrupalblog.lhmdesign.com/drupal-theming-jquery-basics-inc-drupal-behaviors

The javascript code being used by this module is:

// $Id: views_nivo_slider.js,v 1.1.2.5.2.2 2010/06/18 15:04:17 pedrofaria Exp $
Drupal.behaviors.views_nivo_sliderBehavior = function (context) {
  $('.views-nivo-slider').each(function() {
    var id = $(this).attr('id');
    var vns = $(this);
    var cfg = Drupal.settings.views_nivo_slider[id];

    // Fix sizes
    vns.data('hmax', 0).data('wmax', 0);
    $('img', vns).each(function () {
      hmax =  (vns.data('hmax') > $(this).height()) ? vns.data('hmax') : $(this).height();
      wmax =  (vns.data('wmax') > $(this).width()) ? vns.data('hmax') : $(this).width();

      vns.width(wmax).height(hmax).data('hmax', hmax).data('wmax', wmax);
    });

    vns.nivoSlider(cfg);
  });
};

The only error on the page is from jqeuery reading the minified javascript. I don't think this is causing the issue b/c the rotator (what uses this) still works.

Can someone please provide me with some guidance?


texts: Creating a store open hours widget using Field API

texts:
I need an open hours widget that outputs something like:

Mon 8:00am to 5:00pm
Tue 8:00am to 5:00pm
Wen 8:00am to 5:00pm
Thu 8:00am to 5:00pm
Fri 8:00am to 5:00pm
Sat 11:00am to 3:pm
Sun Closed

I think the best way to do this is create a three column field table with day of week, open and close columns. Then create a field widget form with three drop down boxes and a formatter that puts it all together.

Has somebody already done this in Drupal 7? If not, does anybody have any ideas on how to do this best?


texts: How can to make required the fields keywords and description of the metatags module?

texts:
I have a content type and I am interested in make required the field keyword and field description of the metatags module?  anyone knows how can I do it?

The field title is not required.
The field keywords is required
The field metatags is required.

I am working on drupal 7.

Thanks a lot!!

I was trying this code:

function mymodule_form_alter(&$form, &$form_state) {
    if ($form['#form_id'] = 'article_node_form') {
        $form['#validate'][] = 'mymodule_form_validate_fields_metatags';
    }
}

function mymodule_validate_fields_metatags ($form, &$form_state) {
     if (($form['#metatags']['metatags']['description']['value']) == '') {
        form_set_error('Description', t('The field Description is required'));
      }
      if (($form['#metatags']['metatags']['keywords']['value']) == '') {
        form_set_error('', t('The field Keywords is required'));
      }

 }

this code generate an error : NOtice: undefined index.

I have tried this code and not print dsm:

mymodule_form_alter(&$form, &$form_state) {
    if ($form['#form_id'] = 'article_node_form') {
        $form['#validate'][] = 'mymodule_form_validate_fields_metatags';
    }
}

function mymodule_form_validate_fields_metatags ($form, &$form_state) {
dsm("hello");

 }

if no print hello how can test the form_state?  I don't understand what is my error.  Thanks for your help in advance.


texts:
I have set up a site locally .I took db using from live site "Backup and Migrate data".I done all editing in settings.php file for pointing to local db.

It works fine except two errors:

The specified file temporary://fileZGB3Go could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions.
The specified file temporary://filelXQxcP could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions.

Is it db error that these files are imported or something else ?


texts: Check if user registration field is set to visible or hidden on the registration form

texts:
In the user registration form, I have set a certain field say surname as hidden i.e. I have unchecked the checkbox saying "Display on user registration form." as shown below:

Now I want to disable the server side validation for this field. When I print the $form array, the surname field is still displayed. However I am not able to find any such value in the $form array which checks if the value is unchecked or not. Is there any way to figure out if the said field is not displayed on the registration form? Hope I am clear enough.


texts: flag node when clicking on a link in a view (not a flag link)

texts:
I have a view which displays nodes information on a table, each row is a node, in each row I have two links, one opens a node file field in a new window, the other one open a colorbox showing the node body.
I would like to flag the node when the user clicks on any of these two link, but I  can't figure how Ican do this.
Any hint much appreciated.
Thank you.


texts:
Whenever I try to delete a field associated to a content type, I get the following error:

  Drupal\Core\Field\FieldException: Attempt to create a field
  field_cert_fields that does not exist on entity type node. in
  Drupal\field\Entity\FieldConfig->getFieldStorageDefinition() (line 286
  of core/modules/field/src/Entity/FieldConfig.php).

the field field_cert_field is not actually there in any of the content types.

How can i resolve this problem? Even if am getting this error, the field I wanted to delete is deleted.

UPDATE

I have a custom module that defines a custom field in
/modules/certfield/src/Plugin/Field folder .I cant uninstall the module and it says :

  The following reason prevents SSl Cert Field from being uninstalled:
  Fields pending deletion

once i removed the module manually when it cant uninstall via drush .  I guess that makes the issue . Anyway to get rid of this ?


texts:
I am having some issues with my Drupal 7.

Because of a different bug I am having with component or panel, one that is taking over pages and hiding other parts of a page somehow, my login page has been corrupted.

what is supposed to be my /user and/or user/login page looks completely as it should not look. The username and password prompt and input fields are missing because of a component which needs to be removed. This component has somehow managed to cover or hide the thing I need.

The bug that has caused this problem is beyond the scope of this post but I believe that it is probably a requirement to log into the admin panel in order to fix the issue.

How do I log in if I can not get the login prompt page to come up as it should?


texts:
I'm using OutboundPathProcessorInterface. I notice a few odd things about its behavior.

In adding, for example, "/x" to the path, it works in some cases, like admin/structure, but not others, like admin/content or the path I'm interested in, which is defined in a view. This is despite my setting the module's weight to 999 in its install file (before installing), so presumably no other module would be altering the path downstream.
Where it does work, such as admin/structure, the page with the original path loads, with the original URL in the address bar, but all menu links have the altered path.
When I watch it in xdebug, AFTER I alter the path with the query string in $options the URL comes through the function again, with the path set to the original value.


texts: Custom Route not reading session cookie to get current user

texts:
I'm working on creating custom routes that are meant as an API. So far I have created two routes, 1 to log the user in and another to get the current user.
My route file looks like:
ytp_user.api.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::login'
  methods: [POST]
  requirements:
    _user_is_logged_in: "FALSE"
    _format: "json"
ytp_user.api.get_current_user:
  path: "/api/v1/user/me"
  defaults:
    _title: "User API Get Current User"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::getCurrentUser'
  methods: [GET]
  requirements:
    _user_is_logged_in: "TRUE"
    _format: "json"

In my login method I do this:
  function login(Request $request) {
    // Retrieve and validate the sent data
    $data = Json::decode($request->getContent(), TRUE);

    $client = \Drupal::httpClient();
    $host = \Drupal::request()->getSchemeAndHttpHost();
    $url = "$host/user/login?_format=json";

    $req_options = [
      'json' => [
        'name' => $data['username'],
        'pass' => $data['password']
      ]
    ];

    try {
      $response = $client->request('POST', $url, $req_options);
      $success = TRUE;

      $body = Json::decode($response->getBody());

      $session_manager = \Drupal::service('session_manager');
      $session_id = $session_manager->getId();
      $session_name = $session_manager->getName();

      setcookie($session_name, $session_id, []);

      $user = $this->constructUserJson($body['current_user']['uid']);

      $response_body = [
        'sessid' => $session_manager->getId(),
        'session_name' => $session_manager->getName(),
        'token' => $body['csrf_token'],
        'logout_token' => $body['logout_token'],
        'user' => $user
      ];

    } catch (RequestException $e) {
      $log_error = "User API - Call Endpoint\n\n";
      $log_error .= "Request:
" . print_r($e->getRequest(), TRUE) . "
\n\n";
      $log_error .= "Response:
" . print_r($e->getResponse(), TRUE) . "
\n\n";
      \Drupal::logger('ytp')->error($log_error);

      $success = FALSE;
    }

    // Determine response
    return new JsonResponse($response_body, 200, [$session_cookie]);
  }

As you can see, my custom login hits the Drupal login endpoint to actually open a session for the user, but then I do some other custom stuff to send back more information about the user object. I go ahead and add the session data I get from the original login endpoint as a cookie in the request.
However, when I hit the next endpoint /api/v1/user/me with the session cookie provided, I get the error This route can only be accessed by authenticated users.
Why isn't the /api/v1/me/login endpoint using the session cookie to get the current user? How is the current user determined in these requests if not through session cookie?


texts: Why can't you assert the response status in a FunctionalJavascript test?

texts:
If I do this in a FunctionalJavascript test:

    $assert_session->statusCodeEquals(200);

I get:

  Behat\Mink\Exception\UnsupportedDriverActionException: Status code is not available from Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver

Why though?


texts:
I wonder why these results don't merge. This is the result of searching by postcode.
As you can see it returns 2 times the same shop with another deal. I need it to return the shop once with both deals on it. Thanks in advance! Pictures below:


texts: Setting a variable as a class (using set classes) in a region template

texts:
I am attempting to set a common class if any preface region in my theme appears. I am trying to render this with a variable using set classes = [] in the region template in my theme.

So far I have set a variable in a preprocess region like this:

function gratis_preprocess_region(&$vars) {
  // Check to see if any of the preface regions have content and if so
  // Set a common var for use as a class in the region template.
  if (!empty($vars['page']['preface_first']) || !empty($vars['page']['preface_second']) || !empty($vars['page']['preface_third'])) {
    $vars['preface_region'] = '';
  }
}

Then in my theme's region template I attempt to render the variable within the set classes area.

  set classes = [
    'region',
    'region-' ~ region|clean_class,
    region == preface_region ? 'region-preface'
  ]

I am pretty sure I am not doing this the correct way though and it does not work.


texts: How can I use Gmap in Views Exposed filters

texts:
How can I use gmap in the view exposed filter ? So that user can search the result by marking the location on gmap.
I am using gmap 7.x-2.7 and location cck 7.x-3.0-rc2 .
How can I implement this functionality


texts:
I have set clean urls and Boost work great with latin urls like www.mysite.com/yes-this-works.

But when the url have non-latin words like www.mysite.com/μπου-χου this fails.

Any way to solve this?

From my Plesk i see the page name correct but from filezilla the greek characters show ÎµÏÎ¹ÎºÎ¿Î¹Î½ÏÎ½Î¯Î±_.html like this.

Drupal 7


texts: Translate with t() function from spanish as source

texts:
I have a Drupal 7 webpage already developed with all texts in Spanish, but now I want to add English language to the page.
As all my texts are written in spanish, I would like to know what is the best/fast way to translate it to english. I tried with t() function, something like this t('Hola mundo') expecting to be manually translated by me with Drupal translation module (admin/config/regional/translate/translate) to 'Hello world'.

The Drupal 7 documentation says this:
$string A string containing the English string to translate.

So my question is: is there any way to translate with t() from the default language (spanish)?

If it is not possible, how can I translate all the texts to english from spanish?

Thanks


texts:
I am using Rules and Flags modules. I applied a patch to get  the uid is associated with the global flag (otherwise uid is set to 0).  Now how do I get Rules to work with global flags? I am trying to create a rules component, that I can use from Views Bulk Operations, so that if a node in the View was flagged by the current user, only then must the Rule execute on that node via VBO operation. As of now the Rule executes for all nodes. I want to put in some condition or some thing in the Rule, so it checks if the node's global flag's uid is the same as current user and only if so, executes action on that node. Is this possible?

{ "rules_unlock_pages" : {
    "LABEL" : "Unlock pages",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "TAGS" : [ "editorial workflow" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : {
      "locked_node" : { "label" : "Locked Page", "type" : "node" },
      "flag" : { "label" : "flag", "type" : "flag" },
      "flagging" : { "label" : "flagging", "type" : "flagging" }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : { "node" : [ "locked-node" ], "type" : { "value" : { "page" : "page" } } } },
            { "flag_flagged_node" : {
                "flag" : "edit_in_progress",
                "node" : [ "locked-node" ],
                "flagging_user" : [ "site:current-user" ]
              }
            }
          ],
          "DO" : [
            { "flag_unflagnode" : {
                "flag" : "edit_in_progress",
                "node" : [ "locked-node" ],
                "flagging_user" : [ "site:current-user" ],
                "permission_check" : "0"
              }
            }
          ],
          "LABEL" : "Unlock pages locked for edit by current user"
        }
      }
    ]
  }
}

https://www.drupal.org/node/2087797 is the patch I applied to record global flag's uid.


texts: Views: show nodes that share taxonomy term with user

texts:
I have a content type requests with the taxonomy field categories.  I have added categories to my user's profile as well.

I need to create a view that displays all the requests that have category terms the user has selected in their profile.  How do I go about this?


texts: Linked entity references in a content type

texts:
I am unsure if this is possible in Drupal 7, but here is my problem: I have 3 content types, A, B and C.

B and C refer to A through a field field_A (entity reference).

C refer to B through a field field_B.

When creating/editing B, I want the user to select one node A1 of type A, and then, select some node of type B that refer to the node A1.

For example, let's say I have these nodes:

- A1, A2
- B11, B12 referring to A1; B21, ..., B24 referring to A2

A user creates new content of type C, and selects A2: I want the user to be able to select items of type B among the list B21, ..., B24.

I started to use an entity reference view to populate the list of B in C, but then was stuck because it is not possible (or I could not manage to do it) to refer to a field of the edited content type.

Thanks for any help!


texts: Adding the video field to a content type

texts:
We've been using an SWF player for a while. I added the Video module without adding a new content type, just to see if the HTML5 tag worked. It does. However, that obviously doesn't give us an SWF fallback.

I then tried to add a Video content type as per this video tutorial, but when I did it, I didn't see the Video field type or an option for 'video-widget'. Is that a feature present only in Drupal 7, or did I miss something in configuring the Video module?

How do I enable the Video widget so I can have HTML5 and the SWF fallback? Is there an alternative set of HTML to get this done?


texts: How can TranslatableMarkup string output be modified in the theme?

texts:
In comments there's submitted, which is an object from the Translatable Markup Class; run through kint() it looks like this:

I want it to say By @username <time>$datetime</time>, but haven't been able to figure out how it wants me to modify it?

I can get the arguments in preprocess with $variables['submitted']->getArguments(); but that seems less cool.

What's the right way to do this?


texts:
Is it possible to fork current Drupal installation for experiments and have two versions of Drupal with one installation of Apache, PHP and MySQL on Ubuntu?

thank you


texts: How do I get all available form field types?

texts: How do I get all form field types (e.g. "textbox," "select") available in Drupal 6?


texts: Get all user profiles from list of users

texts:
I am evaluating some custom code in a rule. I want to get a list of users, then load all of the associated profiles from the profile2 module. My code below, loads all the users, and I got an array of the UIDs to put into the profile_load_multiple() function but it is just returning one user profile, I want to return all profiles. Eventually I want to compare a term from a field (project resources) in the node 'project' I am creating with a field (resources) that is in each user main profile.  My intention is  using rules to accomplish this.

$users = entity_load('user');
$arrayuids = array();
foreach ($users as $user)
{
array_push($arrayuids, $user->uid);
}
$profile = profile2_load_multiple($arrayuids, FALSE);
dsm($arrayuids);
dsm($profile);


texts: Clean up test payment transaction from drupal commerce site

texts:
I am trying to find an admin page where I can delete all test payment transactions happened on drupal commerce, but could not find it.Need to no if my following plan will create any referential integrity issue after cleanup.

From orders page clean all test orders.

Manually clean the database tables 'commerce_payment_transaction' and 'commerce_payment_transaction_revision' and then using db API clean payment transaction table using
db_truncate('commerce_payment_transaction');
db_truncate('commerce_payment_transaction_revision');

Clean up all tested customer profiles from admin page for the same using bulk operation.

Clean up test users created with the checkout process.

Truncate orders table to start with order id , using again following code.

db_truncate('commerce_order');
db_truncate('commerce_order_revision');


texts: How to configure drupal-nodejs with https?

texts: In drupal-nodejs configuration we have IP with port but how can I have the https for that configured.


texts: How to display a table with results when a batch is finished

texts:
I could setup a nice batch, everything is working well.

But when the batch is finished, I would like to display a beautiful table with the computed results.

I could do it with the drupal_set_message (see below) function, but it is not good enough. [if mandatory, I accept to be redirected to a new page... but how can I pass the result in this case?]

function my_batch_finished_callback($success, $results, $operations) {
    if ($success) {
        $header=[t("col1"),t("col2")];
        drupal_set_message( theme('table', ['header' => $header, 'rows' => $results]));
    }
    else {
        // An error occurred.
        ...
    }
}


texts:
Trying to install the new Drupal-COD Drupal 7 distribution, but got this error:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows

Is this the sort of error one can overcome by increasing my memory_limit in the php.ini file?


texts: Control access to a custom blocks edit page

texts:
I have a small module which creates and adds some custom settings for a block. Now I would like to control access to this blocks edit page. All users should be able to display the block, while changing the actual the configuration only should be available to certain users.
Since I am not able to use hook_permission() I am not really sure how to best solve this so any help would be much appreciated.

Edit

I have tried this without any success:

function MYMODULE_block_info() {
  return array(
    'MYBLOCK' => array(
    'info' => t('MYBLOCK'),
    'cache' => DRUPAL_CACHE_GLOBAL,
    ),
  );
}

When I clear the cache and tries to go to the blocks edit page the url changes but nothing happens. It is like I am still standing on the block overview page?

function MYMODULE_permission() {
  return array(
    'administer MYBLOCK' => array(
    'title' => t('Administer MYBLOCK'),
    'description' => t('Administer MYBLOCK settings.'),
   ),
  );
}

function MYMODULE_menu_alter(&$items) {
  $items['admin/structure/block/manage/MYMODULE/MYBLOCK/configure']['access arguments'] = array('administer MYBLOCK');
}

Edit

If I use user_access() in hook_block_configure() I almost achieve what I want. I don't know if this would be a valid way to solve this problem:

function MYMODULE_block_configure($delta = '') {
  $form = array();
  if ($delta == 'MYBLOCK') {
    if (!user_access('administer MYBLOCK')) {
      drupal_set_message(t('You are not allowed to edit the @block block.', array('@block' => $delta)), WATCHDOG_WARNING);
      drupal_goto('admin/structure/block/manage');
      drupal_exit();
    }
    // Setup form for the block here.
  }
  return $form;
}


texts: How to implement 'Starts With' for exposed filter of User ID

texts:
I have a Page based on a View with an Exposed Filter which is the User ID. So the Search form that appears shows the User ID as the standard 'lookup' of users. I don't want that. I want to be able to have the search field be a standard text field and the results be a 'starts with'.

Eg.

Enter User: [Fra      ]

Would return

Francis
Frank
Friend

How is this done?


texts: How to optimize already uploaded images?

texts:
Is it possible to compress or optimize images that are already uploaded to the server? What about a method to optimize the images on upload?

Goal:

Take all existing images, compress them, and then save them with the same file name and directory so that the image URLs are not broken.
On upload of an image, optimize it so we don't have to repeat #1 above.


texts: How can I organize my content using hierarchical taxonomy?

texts:
My question is rather simple, but I don't know how to do it ?

I want to display a content with various fields, but I want the user to browse "hierarchically". For instance :

Choose brand : BMW
Choose model : BMW / Z3
Choose specific model : BMW / Z3 / 2.0 i

I already made a taxonomy "Brand", a taxonomy "Model", I have a view that shows all brands.

What can I do ?

Thanks for advice, it would help me a lot !


texts:
I ran into this issue on my own plugin and then decided to download the Drupal Example Modules to discover the same issue was happening to me in the 'ajax_example' section.

Ajax calls don't seem to queue, and the last message sent to the server overrides the last.

This is the code I am using. (It can also be found in ajax_example.module.)

function ajax_example_autotextfields($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my first name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['ask_last_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my last name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['textfields'] = array(
    '#title' => t("Generated text fields for first and last name"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we put automatically generated textfields'),
  );

  // Since checkboxes return TRUE or FALSE, we have to check that
  // $form_state has been filled as well as what it contains.
  if (!empty($form_state['values']['ask_first_name']) && $form_state['values']['ask_first_name']) {
    $form['textfields']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First Name'),
    );
  }
  if (!empty($form_state['values']['ask_last_name']) && $form_state['values']['ask_last_name']) {
    $form['textfields']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );

  return $form;
}

function ajax_example_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

This is the screenshot of the page.

After selecting 'first name', 'second name' before 'first name' has time to finish loading.

The 'first name' field is never loaded.

How can I fix this?


texts:
I only want users to logout if they visit the "logout" page. For this I set this in my settings file:

ini_set('session.gc_maxlifetime', 0);
ini_set('session.cookie_lifetime', 0);

But users are still disconnecting from site from time to time and I don't know why.
Is there a better way to tell site to not log out users? What is causing users to be disconnected?

EDIT: I have users that launch site from browser and that launch site through mobile application by rest service(services module). Both types of users are disconnects. I not sure but sometimes when I save some views user is logging out and I recieve message that you have no access.

UPDATE: this part of code ini_set('session.gc_maxlifetime', 0); logs out user. I thought that if it set to 0 it means that user has never been loging out until he not push on logout.


texts: Access negate page is negate to anonymous user

texts:
I have a site where only authenticated users can see the content. So I have set permission for this. Now I have a problem: I need to display a node for the access negate page. But in this moment, my access negate node is negate too.

So how can I display a node for the access negate page ? I have tried with the node view permission module, and a custom type node, without lucky.


texts: Admin custom module not displaying in theoverlay

texts:
How to show the data fetched from the database in the overlay of the admin custom module.
The data are retrieved but not showing in the overlay. Kindly help me out


texts:
I have a Drupal 7 webform, which allows me to download the submissions as a .xlsx. I am able to download the submission forms but all the .xlsx files has 0 bytes. Somehow it works in staging site but it doesn't work in Development and Production. I use Acquia Server for staging and production; for development I use Acquia Dev Desktop. I have tried a few things such as:

I changed my .htaccess memory settings
I added some of the patches from drupal.org
I double checked the configurations of File System's Public file system path and Temporary directory, staging and production settings are identical

Has anyone encountered the same issue before that can lead me for solution? I have spent quite 1 week for this.


texts:
I am creating a module whose purpose is to display some data. I have a input form that saves data to database; that data is then displayed to the user.

I have created a page where that data can be viewed, edited, and deleted.

My problem is that every user can see this. The best thing I have done is using the global $user variable, and verify that the currently logged-in user is the user who created the data being viewed. Every user could see the Edit and Delete tabs, even when no data was created.

I am trying to figure out how I use the permissions in the same way they are used with the content types, where users can edit any node of a content type, or can edit their own nodes of that content type.

How could I resolve this issue?


texts: How do I get the userpoint description to include clickable node link?

texts:
I would like to get a clickable link of the current node stored in the description parameter of the userpoints_userpointsapi

Am using the code below at the moment. Its working fine  but the link shown under the user profile is not clickable.

How can I make this link clickable whenever its displayed in anywhere else on the site for example under the user profile list of points by that user:

$params = array (
    'points' => round($percentage/10),
    'tid' =>16,
    'description' => ''. $node->title .''
    );
userpoints_userpointsapi($params);


texts: Loading a form via AJAX with drupal_get_form()

texts:
I am trying to load a form via ajax, here is the code i use:

JS:

bigPopupBut.click(function () {
        jQuery.ajax({
            url: "http://site/group_create",
            dataType: "html",
            success: function (data) {
                bigPopup.append(data);
            }
        });
})

The group_create is a PHP script that returns me a form, here is the code i used:

$node_type = 'group';
    $form_id = $node_type . '_node_form';
    $node = new stdClass();
    $node->uid = $user->uid;
    $node->name = $user->name ;
    $node->field_city['und']['0']['value'] = $user->field_city['und']['0']['value'];
    $node->field_country['und']['0']['value'] = $user->field_country['und']['0']['value'];
    $node->type = $node_type;
    $node->language = LANGUAGE_NONE;
    $node->path = '';
    node_object_prepare($node);
    $return=drupal_get_form($form_id,$node);
return $return;

The Problem i have is that the PHP callback doesn't just return me the form, but a whole page, with headers, body, so when i append it with JS i get a duplicate of the whole page in my bigPopup DIV.

What am i doing wrong ? how could i just get the form without the surounding page?

Thanks all for the help.


texts: How do I delete/remove a broken configuration?

texts:
I'm using Layout Builder to manage the display of a content type.
I was playing around with the config and adding different things, and something I added caused the page to crash and now I get this error:

  The website encountered an unexpected error. Please try again later.Drupal\Core\Entity\EntityMalformedException: The "node" entity cannot have a URI as it does not have an ID in Drupal\Core\Entity\EntityBase->toUrl() (line 191 of core/lib/Drupal/Core/Entity/EntityBase.php). node_tokens('node', Array, Array, Array, Object)

This error persists every time I click "Manage Display" for that content type; I rebuilt the cache with Drush and cleared my browser cache, but I still get the error when I go to edit the display settings.  I get the error when I log in with a different browser, too, and also when I revert the config.

I am working on this site locally, so I can pull from the dev server, but is there another way to reset my "unsaved changes" locally so that I don't have to wait for the pull to complete?


texts: Is there a module to hide URL path settings by content type?

texts:
Eg. I'd like to let the client see the URL path settings fieldset for Page but not for Slide.

I'm happy to implement it myself, just wondered if someone else already had.


texts: How to omit a view exposed filter if the displayed rows return a single selection value?

texts: Is there an option for that in views UI? If not then how to do it programmatically? In the twig template or a hook?


texts: How to keep URL parameters on subsequent pages after a form is submitted?

texts:
I'm sending a referral form out to my email database and I've got it set up so that their email addresses get passed through and appended to the form URL like this:

http://www.holbrooktravel.com/referral-form?emailid=sarah@holbrooktravel.com

I've got a hidden field in the form that collects the 'emailid' value and stores it with the responses so they can be matched up with our database.

That's working well, but once someone submits their form they're sent to a thank you page (http://www.holbrooktravel.com/referral-form/thank-you) where they can click a button to go back to the form and refer someone else.

I can't figure out how to keep their 'emailid' value on the 2nd referral so those submissions can be matched up as well. If I'm on the right line of thinking then I need to somehow keep the URL parameters on both the thank you page and the link sending them back to the referral form.

Any suggestions would be very much appreciated!


texts:
I am trying to use inline javascript, added with hook_alpha_preprocess_page, to add support to IE.

drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            $("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                width: 420,
                columns: 3
            });
        }
  });', 'inline');

While this loads on the page, nothing is happening. Is this because my selector starts with $? What should I change it to for this to work?


texts: How can I output a Drush report in table format?

texts:
I'm getting into my first drush command and coming up with a ton of things I don't understand. Basically, I need to output a list of image files referenced in my content, and the best seemed to be to output it in a table format so that the different bits of information would be easy to see and distinguish from each other.

I started by following the tutorial and did this (in the COMMAND_drush_command $items array):

    'engines' => array(
        'outputformat' => array(
            'default' => 'table',
            'pipe-format' => 'json',
            // Commands that return deep arrays will usually use
            // machine-ids for the column data.  A 'field-labels'
            // item maps from the machine-id to a human-readable label.
            'field-labels' => array(
                'node' => 'Nid',
                'title' => 'Title',
                'filename' => 'Filename',
                'directory' => 'Directory',
            ),
            // In table format, the 'column-widths' item is consulted
            // to determine the default weights for any named column.
            'column-widths' => array(
                'title' => 20,
            ),
            'require-engine-capability' => array('format-table'),
        ),

That worked fine, because I built an array of output line by line and at the end of the command passed it back to drush which duly printed it. The only problem is that there is a LOT of data, so the command gives the appearance of hanging. So I thought I would try to print line by line and did this instead:

            $result[0] = array(
                'node' => $nid,
                'title' => $title,
                'filename' => end($file),
                'directory' => $directory,
            //    'orphan' => '?',
            );
            $output = drush_format_table($result,false,array('node'=>5,'title' => 20,'filename'=>30,'directory'=>25));
            drush_print($output);

The problem is, that the output is all over the shop, rather than being lined up nicely as it should be.

Where am I going wrong?


texts: get the content type 'machine name' by the 'human readable name '

texts:
I have a content type whose human readable name is Post your blog. How can I get the content type machine name by the human readable name?

Is there a function in Drupal 7, or do I have to query the node_type table to get what I want?


texts:
I have Drupal 7.2 installed, in my site there are menu items like Tech Docs, Doc Tree etc.
For example in Tech Docs I have number of nodes.

After going to Tech Docs page, the breadcrumb looks like

Home >> Tech Docs

After clicking on a node in Tech Docs, the breadcrumb appeared like

Home >> node title

instead, I need the full path.

  Home >> Tech Docs >> node title

How can I solve this? Any ideas???


texts: Toggle Modules on or off at a certain time with Rules

texts:
I'm looking for a way to toggle a Module on or off based on the time of day using Rules. Ideally, the logic behind it would be something like:

IF

The time is between 1700 and 0900 AND Module X is turned OFF

THEN

Turn Module X ON

ELSE IF

The time is between 0900 and 1700 AND Module X is turned ON

Turn Module X OFF

ELSE

Turn Module X OFF

I'd like this to run with each CRON run (15 minutes). Is this achievable using Rules and without going into PHP?


texts: Issue with installing theme via Admin Dashboard (.htaccess issue)

texts:
I am getting "Access denied. You are not authorized to access this page."
at "/admin/appearance/install?token=..." (Only this page alone) while trying to install a custom theme.

I am quiet certain that it's due to the configuration in .htaccess. Unable to read the token query parameter.
I need help editing the .htaccess rewrite rule for installing new theme.
Thank you.


texts: Brotli enabled on Apache Server - CSS not loading using AdvAgg module

texts:
I recently recognized that the CSS on my website doesn't load anymore. My investigation led me to the newly enabled brotli module that my hosting provider activated a few days ago.
There's an issue that described the problem of double compression and also provides a patch for the htaccess file which I applied. The CSS is now loaded again using drupal's default compression but when I activate AdvAgg the CSS doesn't load again (I am using the second option in AdvAgg's configuration - so not the one that is customizable in detail).
Now, I am not sure if this is a bug or not. Anyhow, I couldn't find a solution and some kind of best practice on how to use AdvAgg when brotli is enabled on the server (Apache).
I saw that AdvAgg can handle brotli. If I install brotli on my website and the .br files are sent to the server. Would the server normally compress again or how is the usual behaviour.
Does somebody know how to handle this?


texts: Is there a generic method to retrieve entity IDs?

texts:
I have seen this code suggesting how to return a list of entity IDs:

$query = \Drupal::entityQuery('node');
$query->condition('type', $bundle);
$entity_ids = $query->execute();

but this requires the knowledge of when to use "type" or what "type" is. For example, for user entity i would think setting type to $bundle = 'user' would work - but it gives error.

for terms from a vocab i would expect type to be set to the name of the vocab; but that also gives an error.

Is there a generic method to call for entity_type that would hint at what is required to do a query for entity ids?


texts:
Does anyone know of a module or some other way to allow users to customize blocks or panes (or even regions) in a panel on their profile page (i.e.: the authenticated user could change the color background of the block, or add a picture to the background, could change the color of the borders and font, etc?)

That means the same blocks could be themed differently by all users.

Ideally each block / pane would have a tab with some kind of a drop-down allowing the user to select options to add HTML and CSS on a per block basis.

The site uses Bartik (D7.)

Any feedback on this would be greatly appreciated. :)


texts: How can I display the vocabulary description?

texts:
I have a View which displays content by taxonomy term from a particular vocabulary, and everything is going fine... except for one thing. I would like to display the Vocabulary description in the View header. I have succeeded in doing this by creating an attachment in the View which just does a select on the Vocabulary but this seems to me rather cumbersome and I wondered if there is a better way to do it.

Also, although I have succeeded in attaching my Attachment to the main Page in the View, I cannot see any way of controlling the order in which they appear. As it happens, things appear in the order I want but it seems to be more by accident than anything else.


texts:
I am using the FileField Sources module

One of the features is that it allows you to transfer images from a URL to your drupal folder directly, instead of having to save the image on your computer and then selecting it for upload.

The problem I am having is that it won't let me transfer the file.

  http://anywebsite.com/picture.jpg could not be copied, because the
  destination directory is not properly configured. The folder
  permission is set to 775, as it should be.

I think it has something to do with the Owner/Group of Ubuntu.


texts:
I have two field sets

In the admin/config/regional/translate I have translated the "Account settings" label

But in the Form display I still have the english label:

What can I do to translate the field group labels?


texts:
I have a integer selection list field in my content types with some key|Value options.

0|CEO
1|CTO
2|Manager

now in my template  I want get value. I try {{node.field_positon.value}} but it return me key value (it return 0 or 1 or 2 ).

My question is how can I get value of selection option in template file?

notice: I know I can paly with content.field_position ( but it put some markup wrappers around field),I want get it by node variable.


texts:
This is a very weird one...

I am building a table using

'#type' => 'tableselect'

I have

$header = array('date', 'name', 'email', 'location', 'time');

and

$options[$result2[$i]['id']] = array(
    'date' => gmdate("d / m / Y", $result2[$i]['timestamp']),
    'name' => $result2[$i]['name'],
    'email' => $result2[$i]['email'],
    'location' => $str_location,
    'time' => $str_time,
);

then I am building the table like this...

    $form['table_' . $n] = array(
        '#type' => 'tableselect',
        '#header' => $header,
        '#options' => $options,
        '#prefix' => '

' . $record1->name . '
',
        '#suffix' => '
',
    );

The problem is this: The rows are showing.... but with no data in them!

I can output the $options array and it contains the data I want to see in the table.
I have cleared the cache as mentioned here

Any clues as to why there are the correct rows with the correct columns but with no data?


texts: How can I apply some value with HTML tags to a form element?

texts:
I've assigned some value with HTML tags to a form element, say the element is called name.

When it returns the form, it exactly prints the value along with the HTML. What I want in return instead, is the style applied to the text.

In this what I'm trying to do is hook_form_FORMID_alter().
This is the page where comments are listed(admin/content/comment). In this, for each comment I'm showing the subject comment and author etc. Also a collapsible tree for editing the comment with pre filled values in the fields.

$form['name'] = '<b>Fazeela</b>'
return $form;


texts:
I'm trying to implement an access callback per role for a specific menu item, but other roles can view that menu item also. Any tip is welcome.

/**
 * Implements hook_menu();
 */
function MODULENAME_menu() {

  global $user;

  $items['admin/backoffice/production/taxonomie'] = array(
    'title' => 'Taxonomie',
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
    'page callback' => 'MODULENAME_backoff_taxonomy',
    'access callback' => 'MODULENAME_user_has_role',
    'access arguments' =>  array($user, array('éditeur taxonomie', 'administrator')),
    );

  return $items;
}

function MODULENAME_backoff_taxonomy(){
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $form = drupal_get_form('taxonomy_overview_vocabularies');
  drupal_set_title('Backoffice - Taxonomie');
  return drupal_render($form);
}

function MODULENAME_user_has_role($user,$roles) {
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}


texts:
Following this tutorial https://www.drupal.org/node/2481343 i made a filter where the user can select the nodes, createad from a date till now.

Is there an easy way to make a button with 'show nodes from last year'? I was thinking about a button, switchting between 'last year' and 'all' (in fact a reset of the filter).


texts:
I am using varbase 9.0.0-rc1 distribution
I have successfully uploaded files using the forms while I am logged in. But anonymously I get the following error:
An error occurred while attempting to process /form/tester?element_parents=elements/resume/resume_file&ajax_form=1&_wrapper_format=drupal_ajax: Cannot read property 'extend' of undefined
Any help is appreciated. Not sure if it is related to not being logged in, but it is only happening while not logged in. I would think anonymous users would be able to upload an image on certain forms.


texts:
We just starting out with Drupal 8 and very quickly we ran into our first problem.

How should I alter an existing form in Drupal 8?

We need to alter the save method for the node form to do a redirect to an other page. We want to alter the node form to become something like a multistep form. After the user creates new content they get redirected to a new form (we created) to get some more information.

We solved our problem implementing hook_entity_type_alter().

function mymodule_entity_type_alter(&$entity_info) {
  $handlers = $entity_info['node']->get('handlers');
  $handlers['form']['default'] =    'Drupal\mymodule\Form\MyExtendedNodeForm';
  $handlers['form']['edit'] = 'Drupal\mymodule\Form\MyExtendedNodeForm';
  $entity_info['node']->set('handlers', $handlers);
}

We then created a new form class that extends the node form and alter the save method.

class MyExtendedNodeForm extends NodeForm {

    public function save(array $form, FormStateInterface $form_state) {
      parent::save($form, $form_state);
      $node = $this->entity;
      $form_state->setRedirect('entity.regions.add_form', ['nid' => $node->id()]);
  }

}

This works perfectly, but is it good? If another module does the same, our code does not get executed anymore.


texts:
I have a custom module that implements a custom field.
In that custom field, I have an integer. This integer is optional. The user can insert anyone or leave it empty. If the field is empty, the next number to the largest stored must be assigned on insert.
I understand that to avoid problems of concurrence between the query and the insert, I must use a transaction. Nevertheless, I don't know where to customize the insertion query of my custom field.
I have implemented the FieldFormatter, FieldType and FieldWidget.
Could someone point me in the direction of the file where I should write the customize insert query?


texts:
I am looking for a systematic way to deal with links in Drupal, like there is for images.
For images, you add image field to content type, then install "Insert" module and you can use Wysiwyg to easily insert the image anywhere inside the node content and still have it "manageable" because it is a field.

I am looking for something similar for links (external and internal), but can't think of any existing method. What I have found is to either use "Links" module and have all links displayed at the bottom of the node (via a field) or use Wysiwyg "Link" button and insert links anywhere, but they are unmanaged.

I am looking for a solution where:

All links would be more easily managed - because
they would be kept as fields (most probably "Link" field)
It would be possible to have those links displayed not as a link
list at the bottom of the node, but rather in various places inside node content (like
images with "Insert" module).


texts: What will happen if I restore backup DB with empty session table?

texts:
It seems that only the session is really big compared with other tables.
Is there any bad effect to Drupal site if I restore my backup Mysql file after deleting all the rows in session table?


texts: Drupal 7.2, Views: Adding Author's Name of a node

texts:
I'm sure this is VERY basic, but after 1/2 day or searching, I am finally posting for help.

I have a simple view that is displaying a list of node titles & other fields (view count, comment count, etc). I can't find how to add the name of the author who wrote the corresponding node to a field.

For example- the final result SHOULD look like this-

Title
by: Author Name
Views: #  Comments: #

I have everything else working- just can't figure out how to add the author name field. What's the secret?
Thanks guys!


texts:
I've added the field "field_sdb_profile_basics_forv" to my (default) drupal user profile.

Now I need the IMCE editor to detect and choose the file path, based on that field specifically.

As pr project limitations, I can not:

Add additional modules for functionality (For example Profiles2)
Alter core and or Module code.

Basically, I need to find a way to make a one line request for the Directory path

I am imagening it will be something like this, but can't seem to get the syntax right:

return $user->field_sdb_profile_basics_forv['und'][0]['value'];


texts:
For testing whether Drupal 7 runs on an local nginx server:

One of the user should get more rights than an editor/writer, but less than an admin. Is there a way to create a 2nd specific admin role without certain permissions (e.g. Admin VBO Views)?

Regards, bolshii


texts: Is it possible to get  form submission diff with Diff module

texts:
Diff module, from what i've seen works with node revision differences, not node edit submission diff.

Is diffing any entity-related form submission possible programmatically through Diff module API? Suppose i alter node_form_submit() in my module and i want to record in watchdog the watchdog message the diff if this is a node edit event.

I try with diff_entity_diff($old_entity, $new_entity, $context) but i get no title changes and i'm not sure how to render this output.

Or in other words, which is the best way to get the diff of the submitted values of any form? (compare form_states)

Thanks


texts: How to prevent a View from rendering via a hook?

texts:
I want to prevent an attached view from running depending on some coding parameters.

I've tried using hook_views_pre_view() to prevent it from running, but I can't figure out what options to set on the view to accomplish that. Tweaking attached or rendered doesn't seem to do anything.

function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->attached = FALSE;
      $view->rendered = TRUE;
    }
  }
}

How can it be done?


texts: Drupal 7 multi-site install is half working--What's the next thing to check with a View SQL error?

texts:
Multi-site Drupal 7 and Draggableviews module is giving me heck. I've uninstalled every module and re-enabled the absolute minimum in a sub-site (call this site "wiskey") of my multi-site installation. A search for similar "unknown column" errors frequently pointed to References module. I updated with drush upc.

Since this is a multi-site, I created a Draggableviews test View in the default site (call this site "alpha") and this works, and drags my table like a champ. Which tells me its a problem with the 'w-site' and there's nothing wrong with the Drupal, Views, or Draggableviews modules.

I ran a diff on drush pml of both sub-sites until they were identical. Enabled Seven theme. I re-made the original view. Cleared the Views cache. But, I'm still getting this error,

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

What next?

This= Drupal 7 (recently updated). MySQL. Only one admin user (I checked all the admin/owner permissions to be sure).


texts:
I'm working on a Phonegap app (JS) anndn I'm confused how to pass along the CSRF token with my requests. Would I need to call user/login.json first and then store the token? For future requests how do I pull the token?

$('#page_dashboard').live('pageshow',function(){
  try {
    // Obtain session token.
    $.ajax({
        url:"http://" + website + "/?q=my_services/user/token.json",
        type:"post",
        dataType:"text",
        error:function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function (token) {
        // Call system connect with session token.
        $.ajax({
      url:"http://" + website + "/?q=my_services/system/connect.json",
      type: "post",
      dataType: "json",
      beforeSend: function (request) {
        request.setRequestHeader("X-CSRF-Token", token);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
      },
      success: function (data) {
        var drupal_user = data.user;
        if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
            $('#button_login').show();
            $('#button_logout').hide();
            $('#button_create').hide();
        }
        else { // user is logged in, hide the login button, show the logout button
            document.getElementById("welcome").innerHTML = "Welcome " + drupal_user.name + "";
            $('#button_login').hide();
            $('#button_logout').show();
            $('#button_create').show();
        }
      }
    });
        }
    });
  }
 catch (error) { alert("page_dashboard - " + error); }
});


texts: Hide the display of a field conditionally

texts:
I have the following scenario:

I have many users created from People->Add user

I have a content type (named Project) with the following fields:

--Leaders (Type: Entity Reference to Users)

--Editors  (Type: Entity Reference to Users)

--Price (Type:  Decimal)

--Duration (Type:  Integer)

I want the Price field to be hidden from logged in users belong to Editors field.

The difficult point here is that one User could be Editor to “Project 1” (a node from content type Project) and Leader to “Project 2 ”.

I tried some things with the following modules:  Rules, Field formatter conditions, Views Entity rules, but with no results…

Could you please advise me, how to hide the display of a field considering if the logged in user belongs to “Editors” field for each Project?


texts:
How can I get custom Form API validation to highlight a field the same way the failed #required validation does?  (See attached graphic)

Note Graphic:

1) (Green Line) Company Name is empty.  '#required' Error is noted and field is highlighted red.

2) (Blue Line) Website is incorrect.  'Custom Validation' Error is noted, but field is NOT highlighted.

How can I automatically highlight the 'Website' field on validation fail and remove it upon success?

Currently using: form_set_error('', t('Your website address is incorrectly formatted.'));

See


texts: Reject e-mail address from specific domain in simplenews newsletters e-mails

texts:
i have a lot of spam users request account with mails  on specific domain,i used the User restrictions module to make e-mails on that domains not allowed, but only to the registration .i want to know how can i do the same to the Simplenews module to reject e-mails from specific domains to register in the newsletter.
thatnks


texts: Region for Main page content block field is required Error?

texts:
I have created a custom region called latest. And when I am assigning some block to that region from admin, while saving it returns this error

  Region for Main page content block field is required.

What might be the reason?


texts:
I want to display a form in CTool modal dialog, but failing badly.

When I click link to show modal form, ajax request is started:

POST http://drupal.dev/my_mod/arg1/ajax/arg3

and returns:

Error: Syntax error, unrecognized expression:

          <button type="button"
class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

&nbsp;

I tried to click different link, but gets an error:

  TypeError: Drupal.CTools.Modal.modal is undefined

Code:

function my_mod_menu() {
  return array(
    'my_mod/%/%ctools_js/%' => array(
      'title' => 'Entity Modal Edit',
      'page arguments' => array(1,3),
      'page callback' => 'my_mod_modal_page_callback',
      'access callback' => 'my_mod_modal_access_callback',
      'access arguments' => array(1,2,3),
      'type' => MENU_CALLBACK,
    ),
  );
}

function my_mod_modal_page_callback($entity_type, $id) {
  ctools_include('modal');
  ctools_include('ajax');
  ctools_modal_add_js();

  $form_state['user'] = user_load($id);
  $output = ctools_modal_form_wrapper('my_mod_form', $form_state);
  ctools_modal_render('Edit', $output);
  exit;
}

I'm creating my edit link in custom views_field_handler:

class my_mod_handler_field_links extends views_handler_field {

  function init(&$view, &$options) {
    parent::init($view, $options);

    if (! isset(self::$some_property)) {
      ctools_include('modal');
      ctools_include('ajax');
      ctools_modal_add_js
    }
  }

  function render($values) {

    $edit_link = array(
      'href' => 'my_mod_ctools/some_value1/nojs/some_other_value',
      'title' => t('edit'),
      'attributes' => array('class' => array('mymod-ctools-links', 'ctools-use-modal', 'use-ajax')),
    );

    $links[] = $edit_link;

    $build = array(
      '#prefix' => '
',
      '#suffix' => '
',
      '#theme' => 'links',
      '#links' => $links,
    return drupal_render($build);
  }

  function query() {}

}


texts: Custom JSON api normalizer is not initiated

texts:
I am trying to figure out how to make a custom normalizer for an entity work. I've added the normalizer to my services.yml with the required tag and arguments and run into no errors. But when retrieving the data, my normalizer is not getting instantiated.
What I am trying to accomplish, is to add a attribute to an OrderItem entity, this attribute is dynamic and has to be recalculated everytime the order items gets requests through the JSON API.
My call: http://localhost:3000/jsonapi/order-items/default/438f58e9-37b1-412c-be4d-b843caa8d744
So I get get the requested order item, but my normalizer is never run.
OrderItemEntityNormalizer.php
<?php

namespace Drupal\xxx\Normalizer;

use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\commerce_order\Entity\OrderItemInterface;

/**
 * Order Item Normalizer.
 */
class OrderItemEntityNormalizer extends ContentEntityNormalizer {
  /**
   * Entity interface for this normalizer.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = OrderItemInterface::class;

  /**
   * {@inheritdoc}
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $attributes = parent::normalize($entity, $format, $context);

    $attributes['foo'] = 'xx';

    return $attributes;
  }

}

services.yml
services:
  xxx.order_line_entity:
    class: Drupal\xxx\Normalizer\OrderItemEntityNormalizer
    arguments: ['@entity_type.manager', '@entity_type.repository', '@entity_field.manager']
    tags:
      - { name: normalizer, priority: 1 }

I am not getting any warning or error messages. When adding wrong arguments to the service on purpose it does throw errors, so the services file is being read by the collector.


texts: Custom fileds are not visible on user profile page

texts:
I am fetching those value of this fields from database. But somehow, I couldn't be able to see it on user profile view page.

Can anyone help me to solve it out.


texts: How can I make the coupon code field in commerce mandatory?

texts:
Using D7 commerce coupon/discount modules. I need to make the coupon field mandatory. Every order needs a coupon code entered.

There is no standard "required" checkbox on the field and I tried using conditional fields module to no avail.


texts:
I want to use drupal l() function, but Url doesn't work really well with a view with optional argument.

The view has a context filter, but it is optional. In the routes table it has path /knowledge-base. When I setup view's routing as /knowledge-base/% Routes table starts to receive /knowledge-base/{arg_0}, but it becomes mandatory.

Is it possible to add an argument to the route, so I would be able to construct route /knowledge-base/ID from the code (new Url('route.name', ['arg_0' => $val])), but leave it optional?


texts: Modifying twig file to show elements side-by-side

texts:
I am working on views with embedded filters and my resultant view fields have the below twig setup:

 {% set index = 0 %}

       {% for key, field in fields -%}
        {% if index == 0 or index == 5 %}

        {% endif %}

          {%- if field.wrapper_element -%}
            <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
          {%- endif %}

          {%- if field.label -%}
            {%- if field.label_element -%}
              <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
            {%- else -%}
              {{ field.label }}{{ field.label_suffix }}
            {%- endif %}
          {%- endif %}

            {%- if field.element_type -%}
              <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
            {%- else -%}
              {{ field.content }}
            {%- endif %}

          {%if index == 4 %}

              <button class="button js-form-submit form-submit btn-info btn" type="button" value="Btn1" name="">Btn1</button>

              <button class="button js-form-submit form-submit btn-info btn" type="button" OnClick = "window.print();" value="PRINT" name="">PRINT</button>

          {% endif %}

        {%- if field.wrapper_element -%}
            </{{ field.wrapper_element }}>
          {%- endif %}

        {% if index + 1 == fields | length %}
          Click to go to next page
          {% endif %}
        {% if index == 4 or index + 1 == fields | length  %}

        {% endif %}
        {% set index = index + 1 %}
      {%- endfor %}

In this setup the lable is showing above and then the text beneath. Is there a way to make them show next to each other:

Current output:

 label:
 Answer

Desired output:

label:answer

[![enter image description here][1]][1]

Any help?!!


texts:
The users can logout visinting my-site.com/logout by themselves
But is there any way Admin can logout other users?


texts: custom private message block generates error

texts:
I created a block to generate a private message link to send a message to all the users of a group. I use the php code as the text format on the block body.

<?php
$group = og_context();
$og_id = $group->gid;

$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $og_id, "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();

$result_tmp = $result->fetchAll();
$recipients = array();

foreach($result_tmp AS $tmem)
{
$recipients[] =  user_load($tmem->etid);
}

echo 'Send message to ehood members';
?>

When I use this, It created me a notice message saying -

Notice: Trying to get property of non-object in privatemsg_user_access() (line 335 of /sites/all/modules/privatemsg/privatemsg.module).
Notice: Trying to get property of non-object in privatemsg_user_access() (line 335 of /sites/all/modules/privatemsg/privatemsg.module).

Although it generated the link, It creates the error. I think its somehow related to how $account is mentioned ?

i tried to send global $user instead of $account, but still creates the same error.


texts: Is there a way to import Drupal variables into a the twig template?

texts:
I save a configuration setting using the following code.

$config = \Drupal::service('config.factory')->getEditable('report.settings');
$config->set('id', $values['id'])->save();

Is there a way to use this configuration in my twig template?

I thought about putting PHP code in the template, but it doesn't seem the PHP code added with <?php ?> is executed from the Twig template.


texts:
I've updated a drupal website to the latest 7.x version, and CKEditor stopped working. I had it originally getting //cdn.ckeditor.com/4.5.4/full-all, I've updated to //cdn.ckeditor.com/4.13.0/full but no luck. I've tried to remove and reinstall the module, clear the website and browser caches, etc. I've also uploaded the version and used it from the local disk rather than the CDN (in case there were network issues with the CDN site, but I didn't see any errors).

I'm short of ideas. Has anyone experienced this and has some more ideas for me to try?


texts: Why the cron is launched when I visit the website and why is it taking so much to complete?

texts:
I have a site in development. It has Feeds module installed, with mandatoty Job Scheduler also installed. When I come back to the office to keep working on the site, it takes almost a minute for the webpage to complete. I have checked the log messages, and says that it is the Cron doing its tasks. The Feeds imports are switched off, and configured to launch only on submission (admin), and the cron is scheduled every 3 hours, in times different to those in which the problem appears, apparently it is the visit to the webpage what launches the Cron tasks.

How can I check what is causing the problem?


texts:
I'm using Drupal 8.1.1 with Acquia's Lightning distribution. I need to be able to embed a media entity (a tweet, instagram post, youtube video, image, etc.) and then captured the resultant HTML output in a hook. However, $node->body->value just gives me a weird markup like this:

<drupal-entity data-align=\"none\" data-caption=\"\" data-embed-button=\"media_library\" data-entity-embed-display=\"entity_reference:entity_reference_entity_view\" data-entity-embed-settings=\"{&quot;view_mode&quot;:&quot;media_library&quot;}\" data-entity-id=\"21\" data-entity-type=\"media\" data-entity-uuid=\"ea90ea95-6b7e-4e44-a1a6-4e7baabe3cb7\"></drupal-entity>\r\n"

And rendering the entity through the renderer service gives me the entire output of the node, rather than just the html equivalent of the aforementioned markup.

Is there any way to parse this output and get the actual HTML of the embedded entity?


texts:
Is there any way to find my opened/active sessions and close them in Drupal?. Like in Gmail, If there already exists a session for the logged in user they can be notified like the follows and they can close all active sessions of them except the current session.

  open in 1 other location - Details

Similarly as an Admin I would like to view active sessions for all users. I know that all sessions are stored in sessions table. I can retrieve them by creating a custom module. But I wonder is there any module available for this


texts: Getting JQuery Masonry to work with Drupal 7 Views

texts:
I want to do this without porting the fluid grid module to 7 from 6. I can't for the life of me get a view page of images to work with Masonry.

Does anyone has experience with this and know how to get it working with just masonry.js and not a module?

Thanks


texts: Get interface translation LID (Locale Id?) using source string value

texts:
I'm using User interface translation in English to override system strings like Drupal 7's String Overrides module did. Works great. However, in my custom module, as I edit strings that run through the t() function, the Source string table in User interface translation is filling up with unused strings.

I'm writing a simple function to delete unwanted source strings one-by-one. The post at http://www.drupal8.ovh/en/tutoriels/89/delete-a-source-string-and-target-translations-drupal-8 provides code for deleting a translation once you know the LID (Locale Id?), which it suggests you get by inspecting the HTML of the displayed User interface translation page.

Question: Is there a way to look up the LID for a source string using the text of the source string?

I've read many posts, but don't see any that suggest how to do this.


texts: Add a variable amount of time to a date field via rules

texts: I'm trying to add a time duration field value (integer type representing seconds) to a date field using rules, but I'm not able to reference the duration field when it comes time to calculate/edit the date value (presumably because they are of different field types).  I can do things like "+30 days", but really what I want to do is "+$x days".


texts: How do I attach an existing file to a node?

texts:
Here's my problem. I have a D6 site which has been in production for a number of years, and in consequence has used various methods (and modules) for displaying images within body text of book pages. The latest of these modules is IMCE. Up to now (unless I've missed something), none of these mechanisms had any management of the links to images incorporated in the body text. As a result, I have a lot of links pointing to various places in my files directory,

With the arrival of Drupal 8, I've discovered "managed files" and the possibility of using "Inline Images" with CKEditor, such that files in the body text are properly managed, and you get a display in the Files listing of where the images are used.

Since this suits my use case fine, I think I don't need any alternative modules any more. However, here comes the problem: having migrated the site from D6 to D8, the physical directory where the files are kept has changed and since all the files have been copied over, all the body text links are broken.

What to do? Well, I decided to write a drush command which would look through all the body texts that contain <img> tags, extract the image file references, find the real file, create a managed file entity, attach that entity to the node, change the <img src="my file ref"> and save it back to the body.

Thanks to Berdir's friendly advice, I abandoned the original idea of using SQL to go directly through the table, and decided to have a go at Entity Queries instead (first time ever!). So we have this:

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'book');
$entity_ids = $query->execute();
foreach($entity_ids as $nid) {
  $node = Node::load($nid);
  $body = $node->get('body')->getValue();
  $body_text = $body['value'];
  $summary = $body['summary'];
  $format = $body['format'];
  }

So far so good. I won't bore you with the details of how I extract the file name and directory, but I can do this. So now I want to create and save a file entity, and then attach it to the node. This code creates the file entity (but see Berdir's answer below, not everything is necessary here):

    $file_name = end(explode("/", $src));
    $file = entity_create('file');
    $file->setFilename($file_name);
    $file->setFileUri('public://images/'.$file_name);
    $file->setSize($size);
    $file->language('en');
    $file->isNew();
    $file->setTemporary();
    $file->save();

(I confess that I'm really struggling to get my head round the Drupal 8 API and object programming...).

This actually works, it does create a temporary file entity which shows up properly in the Content list (except the MIME type is missing, that needs adding).

However, this is probably not the way to go because there surely must be some mechanism for creating the file entity and attaching it to the node without going through all this - just as CKEditor does when you add an inline image.

I've tried getting a list of all the methods proposed by the Node class, and thought maybe $mynode->referencedEntities() would show me the way - but this doesn't include inline images (I tried with a new test node that does contain an inline image, and it doesn't show here). Should it perhaps appear via a link to the body text as a field entity? And if so, where to go to get this information, and manipulate it?

I have found this in the Editor core module, perhaps this is the way to go?

function _editor_record_file_usage(array $uuids, EntityInterface $entity) {
   foreach ($uuids as $uuid) {
    if ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid)) {
    if ($file->status !== FILE_STATUS_PERMANENT) {
      $file->status = FILE_STATUS_PERMANENT;
      $file->save();
    }
  \Drupal::service('file.usage')->add($file, 'editor', $entity->getEntityTypeId(), $entity->id());
    }
  }
}


texts:
I'm having a performance crisis with my front page.  I have the standard drupal cache enabled which works great for anonymous users, but my front page is practically unusable for logged in users.

The front page doesn't contain any user-specific information, so it would be great if the front page was always cached version for all users.

Actually, there is a user account link in the header which is user-specific, but I'd be willing to forgo that (display as anonymous) for the quick, all-encompassing solution.  I'm working on a real caching solution for logged in users, but I'd like a quick fix like this.


texts: Contextual Filters within Block Display?

texts:
using d7.4

I am trying to setup a block on my node pages that will show:
View Count
Comment Count
Flag Count

My node paths are setup as:
category/categoryname/nodetitle

I know I need a Contextual Filter to link this view to the Node Title (right???) - but how do I designate a path for that within a block? I know I can name a path with a View-Page Display- but I need this to be shown inside a block, not a page.  What am I missing here?

Thanks for the reply!  This newbie appreciates it!


texts:
I am getting the following error when trying to create an omega-sub-theme on my local machine (OSX) using drush on Acquia Dev Desktop.

PHP Fatal error:  Call to undefined function _omega_tools_transform_theme_name()

Install process I followed goes:

Set Name
unique machine name
Omega (HTML5 base)
Default Starterkit
Destination: sites/all/themes
keep starterkit read me files
enable theme/ set as default
download libraries defined in libraries.make

Fatal error occurs here.


texts: How can I require multi-user approval for a node?

texts:
I have a created a "Team" node type, and I'd like a single user to "invite" people onto the team, but require each team member's approval.

I currently have workflow states of "Approved" and "Unapproved" linked to the "Team" type, and an unlimited "User Reference" field attached to the "Team" type, but I'm not sure how to use Drupal's built-in approval mechanism appropriately. I could create an intermediary node type ("RSVP", maybe) with an "Approved/Unapproved" boolean field (or Workflow status, I suppose) and a "User Reference" with limit 1, and then link the RSVPs to the "team" type., but this seems a little kludgey.


texts: Get image file values in $form_state in media entity form

texts:
I am trying to get the values from an uploaded image inside a media entity during form submit.
Where my approach doesn't work:

When first uploading an image in the media_image_add_form form.
When editing an existing media entity and removing, then uploading a new image and trying to save.

My validation only works when editing and submitting an existing media entity (without changing the uploaded image file).
Here is my entire code for brevity, though it may be long, MYMODULE.module:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'media_image_add_form' || $form_id == 'media_image_edit_form') {

    if ($form_state->getFormObject()->getEntity()->get("field_media_image")->entity) {

      $form['#validate'][] = '_MYMODULE_validate';
    }
  }
}

/**
 * Validates submission values in the FORM_ID() form.
 */
function _MYMODULE_validate(array &$form, FormStateInterface $form_state) {

  // $imageEntity = File::load($form_state->getValues()['field_media_image'][0]['fids'][0]); // Tried File::load here as well.
  $imageField = $form_state->getFormObject()->getEntity()->get("field_media_image");
  $imageEntity = $imageField->entity;
  $imageFileSize = $imageEntity->getSize();
  $imageFileMime = $imageEntity->getMimeType();
  $imageFileName = $imageEntity->getFilename();
  $isIssue = FALSE;
  $showConditionalMessage = FALSE;
  $ciuMessage = "";
  $ignoreWarnings = $form_state->getValues()['field_ignore_warnings']['value']; // Field set on media image entity type.

  // Conditional issue.
  if ($ignoreWarnings === 0 && $imageFileMime === "image/jpeg" && $imageFileSize / 1000 > 150) {
    $isIssue = TRUE;
    $showConditionalMessage = TRUE;
    $ciuMessage .= "
Conditional: This JPG file size is larger than 150kb, have you optimized this JPG image?
";
  }

  // Conditional issue.
  if ($ignoreWarnings === 0 && $imageFileMime === "image/png" && $imageFileSize / 1000 > 200) {
    $isIssue = TRUE;
    $showConditionalMessage = TRUE;
    $ciuMessage .= "
Conditional: This PNG file size is larger than 200kb, have you optimized this PNG image?
";
  }

  // Non-conditional issue.
  if (strpos($imageFileName, ' ') !== false) {
    $isIssue = TRUE;
    $ciuMessage .= "
Filenames cannot contain spaces.
";
  }

  // Non-conditional issue.
  if (strtolower($imageFileName) !== $imageFileName) {
    $isIssue = TRUE;
    $ciuMessage .= "
Filenames need to be in all lowercase.
";
  }

  if ($isIssue) {
    if ($showConditionalMessage) {
      $ciuMessage .= 'To ignore conditional errors, check the "Ignore conditional errors" checkbox below.';
    }
    $form_state->setErrorByName('title', new FormattableMarkup($ciuMessage, []));
  }
}

One caveat for using hook_form_alter() is that some of the errors are conditional, and I would like to provide a field on the media entity type to allow ignoring some of the errors.
How can I get the uploaded file/values in $form_state when adding an image to a new media entity, or adding a new image to an existing media entity?


texts: Execute a file in the body of a specific content type

texts: How to load the file, which contains css, javascript and html, in the body of a specific content type?


texts: preg_replace() not working on node title in hook_preprocess_page()

texts:
Here's code from my module:

function mymodule_preprocess_page(&$variables) {
  // load the node object
  $node = node_load(arg(1));
  $fied = $node->field_building_sell['und'][0]['value'];

  // regexp
  $pattern = '/(\w+\s\w+,\s\w+\s.{3}\s\/\/\s\w+)(.*)/i';
  $replacement = '$1';
  $subject = $node->title;
  $replaced = preg_replace($pattern, $replacement, $subject);

  $variables['title'] = $replaced;

  dpm($replaced);
}

My node title looks like this:

building Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29

But i still get the full node title unchanged. Is preg_replace() not working in preprocess_page hook?

UPDATE

I have noticed, if i replace:

$subject = $node->title;

to

$subject = 'building Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29';

It works! But it's not working with $node->title, though, node title output is exactly the same as the string i posted above.


texts: webform: additional options for components

texts:
Im trying to add additional options for webform component but I seem to be unable to read the data out. I successfully managed to save the data into "extra" inside the db. But I'm unable to read it out again.

what I basically did is this:

function webform_maxlenght_form_webform_component_edit_form_alter(&$form, &$form_state, $form_id) {
$form['extra']['message'] = array(
  '#type' => 'textarea',
      '#title' => 'Message',
      '#default_value' => isset($form['extra']['message']) ? $form['extra']['message'] : NULL,
  );
}

It saves it perfectly fine into the database under the field "extra" like I wanted but I'm lost as to how to use it later.

Any help is greatly appreciated, if I'm going into a completely wrong direction please say so


texts: Changing a dropdown based on another one

texts:
I've got a content type with a dropdown with some states. And I've got another list (radio buttons) which should change the dropdown based on the selected item. Is that somehow possible?

I've tried Conditional Fields, but that didn't do what I want. Maybe rules? I'm kind of newbie with Drupal.


texts:
I have a content type = Article. There I have 2 field. What I want is, If field 1 is empty or does not contain any value, replace this field with field 2, (with same css and html structure) else keep showing content of field 1 by default.

Is there any way to this in D8?


texts:
Is there a way to make Open Atrium 2 look a bit more like Open Atrium 1 (e.g. display icons for the sections)?
We'd like to make it easier for our users to switch. Besides OA 1 looks friendlier in our opinion.


texts:
Does anyone know of a Module for Google Tag Manager?

I found something under development here:

https://drupal.org/node/2070317