texts: Route parameter upcasting and route access?

texts:
Original problem:

I am trying to do a couple of (seemingly) simple things to convert a module I made in Drupal 7 to Drupal 8 (RC1).

First I will note I am using the File Entity module in Drupal 8, which may or may not be stable/complete.

I want to add a tab on a File entity (much like Edit or Archive) that lets me trigger processes, related to the data contained in the file (its a spreadsheet).

So far, I have been able to stumble through getting a route defined and a tab to appear.

mymodule.routing.yml:

entity.file.import_data:
  path: '/file/{file}/import-data'
  defaults:
    _form: '\Drupal\datacenter\Form\ImportDataForm'
    _title: 'Import Data'
  requirements:
    _permission: 'access content'
  options:
    _admin_route: TRUE

mymodule.tasks.yml:

entity.file.import_data:
  route_name: entity.file.import_data
  title: 'Import Data'
  base_route: entity.file.canonical
  weight: 3

Well okay. So far so good. Not the most robust thing in the world, but I am still working my way through unfinished docs and such. From here, I have a new tab on a File entity form, right next to Edit.

First, how can I change the permissions to not be access content, but to check access to see if the current user has access to edit the file in question? If I change _permission to _entity_access: file.update (as I have seen in File Entity) the tab vanishes, and direct URL access returns Access Denied (even as user 1). Do I have to implement something extra to make that work?

Second, I don't seem to be receiving the {file} argument or file entity object in my form builder.

Form class:

namespace Drupal\datacenter\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ImportDataForm extends FormBase {
  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'datacenter_import_data_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state, FileInterface $file = NULL) {
    // fields to be defined

    return $form;
  }

 // extra code removed

buildForm doesn't have an entity (file) argument. What am I missing? I thought upcasting basically happened if the object ID was in the route (like node, user, etc).

Also, is this even the way to go about it? Basically this screen will do a few things, it will inspect the file object, check to make sure the mime is right, parse the csv or excel data, and read it back on the screen in the form of options. Whatever the user ticks off, will kick off a series of batches. Where would those batch functions go? In this class? In another file? I also see other classes like ContentEntityForm, EntityForm, etc.. which one should I be using?

I have all of this working great in Drupal 7, I am just having trouble getting momentum converting it over and finding what I need.


texts:
I have a regular Drupal form that is not in a modal. When the user submits the form, a ctools modal popup opens (as per http://drupal.org/node/1482968).

My question is, what is the best method for passing form input to the modal? So that e.g. if the user enters their name ("Alex") in the form, the modal popup can read, "Welcome Alex!" ?

I am using Drupal 7 and the latest stable release of Ctools. (Also, I've asked this question in the ctools issue queue at http://drupal.org/node/1556856, but haven't had a reply in twenty days.) I've been trying to crack this one for a while, so would be incredibly grateful for any help!


texts: How can I disable the cache for a specific page or have the cache ignore query params?

texts:
I need to disable the cache for a specific page, or get the cache to ignore query params. I have tried this, but it does not disable the cache for me https://www.drupal.org/project/page_cache_query_ignore
After trying multiple ways to disable the cache for a specific page or even the whole site I have nothing that works.
I have tried all of these in settings.php
$settings['cache']['default'] = 'cache.backend.null';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['entity'] = 'cache.backend.null';

There is also talk of using \Drupal::service('page_cache_kill_switch')->trigger(); but I am unsure where to place this to disable the cache for a regular page.
This is for the search page, that uses query params for the search query. Drupal 8 is caching the page so each visit to the search after the first search always shows the results for the first search.
The header for Drupal dynamic cache is always a HIT
X-Drupal-Dynamic-Cache:    HIT


texts:
I am using an image as my site background that is of size 2.7MB. Because of its image size alone it takes 7+ seconds for the page to load.

Question: Can/How do I cache this background image at user's browser caches that it is not downloaded every single time?

Basically, i understand that first load will be slow but if cached - subsequent loads would be faster then.


texts:
I am using facebook album fetcher module. It shows an error message

  An unknown error occurred while trying to fetch the album (empty reply).

Can anyone tell me how to resolve this issue.


texts: Default search does not bring node reference field.

texts: I have a node reference field in one content type.I am not getting the search result if I do search with this node reference field value.this field is an auto complete field.What i need is if i search this node reference field value i want the node that belongs to this field.


texts: How do I prefill a paragraph field in a node form?

texts: I have a content type with a paragraph entity reference field and every time a user is going to add a node of this type I want to have the paragraph field already open and prefilled. I've tried with hook_form_alter, but it's not opening the paragraph form with prefilled values.


texts:
I want to store all the uploaded media files on a different sub-domain on the same server (for CDN origin purpose).
I think I can point drupal to upload files to this location (using the File System configuration > "Public file system path ") but how do I config it to use the correct URL?
I guess I can do some htaccess redirects but it makes it more complex with multisite installation.

Does the CDN module does that?

Thanks,
Bnaya

Edit: I use Media module and only needs the files uploaded by it will use the CDN, I will handle the theme files.


texts: Add text above the registration form on user/register page

texts:
Is there a way to add a message above the Registration Form?

I know you can edit the field by going to "Configuration/People/Account Setting/Manage Field", but how about a message above the form?

Thanks


texts: Execute a custom shell script before the aegir verify

texts:
Every actions in aegir trigger a verify.

I would like to automatically execute a shell script before that verify (rsync of plateforms).

How could I proceed ?


texts: I need to change the time component of a webform from select list to a textfield. Something like a datepicker for a date component. Any help will be really appreciated.


texts: What is the correct way to rename an uploaded file using tokens?

texts:
I am building a webform. I have a Name field that uses first and last name.
I have an image upload field where I want to rename the image to lastname-firstname.jpg.
In the properties for the file upload, I selected Rename files for the pattern [webform:element:name:last__title]-[webform:element:name:first__title].
When I test this using John Smith, the file is getting renamed, but it is being renamed to last-name-first-name.png instead of smith-john.jpg.
I'm guessing I'm doing something wrong with the pattern, but I don't know what.
This is the field definition.
name:
  '#type': name
  '#title': Name
  '#title__access': false
  '#first__title': 'First Name'
  '#middle__access': false
  '#last__title': 'Last Name'
  '#suffix__access': false
  '#degree__access': false


texts: In a Drupal 7 block, how to enable calling a Javascript function using behaviors

texts:
I am trying to put code into a block that contains a Javascript onclick handler.  Have been trying to figure out how to use drupal_add_js, but cannot figure out how to make an onclick function work. I believe I may need to use Drupal behaviors.

I have read the documentation, but it is not clear. Here is what I am trying but doesn't work. Any help would be appreciated.

drupal_add_js('jQuery(document).ready(function() { $("#trial").click(function() { alert("Handler called." ); } ); } );', 'inline');


texts:
I have developed websites using Drupal since 1998. Getting Simplenews to send HTML formatted emails in D8 has been the most frustrating experience I've had in all those years. I am very upset. I find the current state of D8 documentation to be quite shoddy overall, not just Simplenews. Here's a glaring example of what I'm talking about: I'm building a D8 site using D8 modules. I go to the README file in the simplenews directory and I'm reading all about how.

  You can customize the theming of newsletters. Copy any of the *.tpl.php
      files from the simplenews module directory to your theme directory. Both
      general and by-newsletter theming can be performed.
      Theme newsletter body:

  simplenews-newsletter-body.tpl.php (for all newsletters)
  simplenews-newsletter-body--[newsletter_id].tpl.php
  simplenews-newsletter-body--[view mode].tpl.php
  simplenews-newsletter-body--[newsletter_id]--[view mode].tpl.php

Here's some news for the module developers: None of that exists in the D8 module! WTF, really? These are D7 instructions. Not very helpful esp since that README file contains some of the most complete and detailed instructions on this aspect of simplenews-- if you're using the D7 version, that is..

I have spent an all-nighter and several full days on configuring this. I'm using sipmplenews Version: 8.x-1.0-alpha2, mailsystem Version: 8.x-4.1, mimemail Version: 8.x-1.x-dev and smtp Version: 8.x-1.0-beta2. No matter what recipe I follow from the myriad of posts on this subject, this is what my HTML email messages look like when they arrive in my inbox: HTML tags visible and absolutely no formatting.

Testing 1234
 Testing 1234

View this message in your browser HERE.

 MICHAEL “SKEETER” PILARSKI

 <img alt="Friends of the Trees Masthead" src="example.com/sites/default/files/images/top-fts.jpg" style="width: 100%` ...

If anyone has this working or if there is a sympathetic developer out there, hear my plea: Someone please create a step-by-step basic simplenews configuration that anyone can follow to get simplenews to successfully send HTML formatted emails from a D8 website. If it was a configuration that was just enough to get it to work (with a designated theme and any other variables set), user customization could follow once a successful email has been sent This whole thing has worn me out.


texts: Call AJAX function in the beginning not just after change

texts:
I've built a form that uses ajax to determine the number of text fields there should be based on a select field. It successfully adds the text fields based off the select field when it is changed, but it does not add the fields in the beginning before there is a change.

    $this->configuration['test'] = '3';
    $form['columnNum'] = [
        '#title'   => t('Number of Columns'),
        '#type'    => 'select',
        '#options' => [
            1         => '1',
            2         => '2',
            3         => '3',
            4         => '4',
        ],
        '#default_value' => $this->configuration['test'],
        '#empty_option'  => t('-select-'),
        '#ajax'          => [
            'callback'      => [$this, 'columnCallback'],
        ],
    ];

public function columnCallback(array&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $number   = $form_state->getValue(['settings', 'columnNum']);

    for ($i = 0; $i < $number; $i += 1) {
        $columns[$i] = [
            '#type'  => 'textfield',
            '#title' => t('Column Title'),
            '#value' => $this->configuration['test'],
        ];
    }
    $content[] = [
        '#type'        => 'container',
        '#attributes'  => ['id'  => 'column_wrapper'],
        'columnTitles' => $columns,
    ];

    $response->addCommand(new ReplaceCommand('#column_wrapper', $content));
    return $response;
}

I've attempted lines this

$this->columnCallback();

But that failed.
Is there a way to get an ajax callback in the beginning before the field as well? Or is there a better way to do this entirely?


texts: Add on domain does not have access to "../privatefiles" at public_html level

texts:
I have a Drupal site that accepts private file uploads from some authenticated users.

The directory where those files are stored is privatefiles and it is located above the www directory, at the same level than the public_html directory. In the file system, the private file system path is defined as "../privatefiles"

That seems to work well.

I But I am transferring the site to another hosting company and putting it there as an add on domain to an existing one. The uploaded private files are no longer visible.

To make the add on site, I had to create another directory. The new directory is example1.com/example2.com If I move the private file directory one level down (i.e. under the public_html directory, then the private files become visible again.)

The only problem is that those files are now accessible from the web.

Does anyone know why this is so? How can I keep the private files at the same level? Should the "../privatefiles" be written differently? Or is this issue a limitation imposed by the new hosting company?

Any pointer for this would be greatly appreciated. :)


texts:
We're using the Views XML Backend module to display XML data in our Drupal site from an XML-based Web API.  (We actually have an integration tool wrapping the API, so we can transform data going into the Web API call.  For example, I'm transforming JSON data into XML.)

I'd like to be able to use pagination in Drupal so that the users see that they are viewing results 1-20 of 500 results (for example), then pass the pagination information along to the Web API.  The API (which was written in-house) can take the number of results to retrieve and either the page number or the first result to retrieve.

How can I achieve this?

I'm relatively new to Drupal, so please be patient.  Thanks!


texts: Is there a 'official' place to put PHP snippets?

texts:
If I wanted all PHP removed from the front end (meaning not in views, not in the body of blocks), but someplace hidden in the background, is there a 'official' recommendation for doing so?

Drupal's framework is PHP so I figured it would have some sort of standard for this type of thing, but it doesn't appear to be the case.


texts: Using hook_query_TAG_alter to add 'OR' queries to EntityFieldQuery

texts:
I need to use the OR operator on an EntityFieldQuery which I understand can only be accomplished via addTag and hook_query_TAG_alter.

My query at present:

$query = new EntityFieldQuery();
$query->propertyOrderBy('created', 'DESC');
$query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'news')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_pub_year', 'value', $year, '=');
if(isset($_GET['country_id'])){
    $country = $_GET['country_id'];
    $query->fieldCondition('field_related_country', 'target_id', $country, '=');
}
if(isset($keywords)){
    $query->addTag('search');
}
$result = $query->execute();

Without much more than a rudimentary knowledge of Drupal, I would expect that the following function, inserted into my template, might work:

function hook_query_search_alter(QueryAlterableInterface $query){
    $or = db_or()
      ->fieldCondition('title', 'value','%'. $keywords .'%', 'LIKE')
      ->fieldCondition('body', 'value','%'. $keywords .'%', 'LIKE');
    $query->condition($or);
}

Yet, it seems to do nothing...

I'm having equal luck googling this problem. Appreciate any suggestions.  Thanks.

Update:

I moved the alter function into a module and re-wrote it to look like:

function modulename_query_search_alter(QueryAlterableInterface $query){
    $terms = $query->getMetaData('terms');
    $words = "%".$terms."%";
    $or = db_or()->condition('body', $words, 'LIKE')->condition('title', $words, 'LIKE');
    $query->condition($or);
}

but I now get an unknown column body error.  Removing that condition works correctly and results are filtered by title field. Not sure what the deal is with that...


texts: Displaying a block only for nodes of a specific content type, how do I check the content type using PHP?

texts:
I have a block which I would only like displayed on a KYN node. I'm currently using the option to display the block only on pages with "node/*" which worked when I only was using one node type but now that I have two (kYNs and Pages) I need to come up with a solution.

I'd like to use some PHP that returns TRUE when the content type of a node KYN.

How can I achieve this?


texts: is it ok to use system_check_directory in a custom module?

texts:
I love the easiness of applying system_check_directory to a form field. You just add

'#after_build' => array('system_check_directory'),

to your field definition in a form and it does it all :

check if the dir exists

create it if not

check if it is writeable
report to the user

As seen (on TV) in the drupal core.
Indeed, it probably does a little too much - the extra .htaccess file ... Could that cause any problem ? The description of the function looks almost as if it was only for the system form.


texts: Exposed form block disappear when views has no results

texts:
I created a view template for my website in which i put my exposed form block with twig tweak module. It works when there is at least 1 result.
But when my view has no result, the exposed form disappear so i have to reload the page.

{#
/**
 * @file views-bootstrap-grid.html.twig
 * Default simple view template to display Bootstrap Grids.
 *
 *
 * - columns: Contains rows grouped by columns.
 * - rows: Contains a nested array of rows. Each row contains an array of
 *   columns.
 * - column_type: Contains a number (default Bootstrap grid system column type).
 *
 * @ingroup views_templates
 */
#}
{%
  set classes = [
    'views-view-grid',
  ]
%}
{% if title %}

{{ title }}

{% endif %}

Nos formations

 Découvrez toutes les formations proposées par le CFA

----->  {{ render_block('formulaireexposerecherche_formationpage_1') }} <---------------

    {% for key, row in rows -%}

{{ view.style_plugin.getField(loop.index0, 'field_type_de_diplome') }}

            {{ drupal_field('field_type_de_diplome', 'taxonomy_term', tid) }}

{{ view.style_plugin.getField(loop.index0, 'field_abreviation_recherche') }}

          {% set lienContenu = view.style_plugin.getField(loop.index0, 'view_node') %}

{{ view.style_plugin.getField(loop.index0, 'field_image_principale') }}

{{ view.style_plugin.getField(loop.index0, 'field_localisation') }}

    {% endfor %}

I've tested all the solutions i found on internet but nothing works.

Sorry, I'm beginner on drupal.

Thanks !!


texts: How to modify the comment body while in comment.tpl.php

texts:
At a Drupal 7 website dedicated to a card game I'm trying to color the special characters for hearts and diamonds in all plain_text comments red.

Since I haven't found the way to modify the text filter yet, I'm trying to "hack" the file themes/bartik/templates/comment.tpl.php as workaround by inserting the 5 lines below:

<div class="content"<?php print $content_attributes; ?>>
  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['links']);

    $body = $comment->comment_body[LANGUAGE_NONE][0]['value'];
    $body =  str_replace('♦', '♦', $body);
    $body =  str_replace('♥', '♥', $body);
    print "\n\n";
    $comment->comment_body[LANGUAGE_NONE][0]['value'] = $body;

    print render($content);
  ?>

In the HTML comment between  above I can see that the string substitution has worked okay.

But the comment itself isn't modified.

I've tried modifying both $comment->comment_body[LANGUAGE_NONE][0]['value'] and $comment->comment_body[LANGUAGE_NONE][0]['safe_value'] but the comment is still unchanged.

I've studied the output of print_r($content) and var_dump($content) but still can't figure out how to modify the comment body.


texts: How to create report to list users who change only specific field?

texts:
I have a content type with several fields which are updated manually over time by different users.

Let's say, for example, the content type name is Ticket
and the fields in this content type are:

Ticket Status
Ticket Resolved Date
Ticket Escalation Date (default empty)

Every time a user changes a field, a revision is created automatically.

How can I create a report (using the Views module) to list the users who only change the field "Ticket Escalation Date" from empty to some value?

Note: The site exists for quite some time already and contains data. So a report about these cases that were created in the past is needed also, based on the current design and existing data.


texts: How do I show a field value of a referenced field separately?

texts:
I can not write english correctly and very well,I am sorry about this issue.please help me for solving my problem.

How do I show a field value of a referenced field separately with the Views or the Rules module?

I want to show only the referenced field value to visitors.for example :

I have a field (field_describtion) with label about you , So I want to reference to this field_describtion and when see the content field_describtion only show to visitors.
I add referenced field_describtion from a content type and after search on that field and select a field_describtion value when click on referenced field value linked to referenced node.BUT I want to after click on referenced field (referenced field_describtion) link to a page that show only field_describtion (with label about you) to visitors.

I any way to work with this idea ?

My drupal version is 7 and I used entityreference module.


texts: Removing cached reference to missing table: services_user?

texts:
When trying to update user profiles via the Services module (not via drupal) - calling mysite.com/drupalgap/user/1.json as a POST with correct parameters -  I'm getting the following error:

  500 Internal Server Error :  An error occurred (42S02): SQLSTATE[42S02]:  Base table or view not found: 1146 Table 'mydbname.services_user' doesn't exist

I've cleared all my caches but the problem persists. In fact, the cache table rebuilds itself with the a serialized reference to a services_user table in schema row. The line is huge, but here's the part with that reference:

s:13:"services_user";a:3:{s:6:"fields";a:3:{s:3:"uid";a:3:{s:4:"type";s:3:"int";s:8:"unsigned";b:1;s:8:"not null";b:1;}s:7:"created";a:3:{s:4:"type";s:3:"int";s:8:"not null";b:1;s:7:"default";i:0;}s:7:"changed";a:3:{s:4:"type";s:3:"int";s:8:"not null";b:1;s:7:"default";i:0;}}s:6:"module";s:8:"services";s:4:"name";s:13:"services_user";}s:8:"smart_ip";a:5:{s:6:"fields";a:8:{s:8:"geoip_id";a:3:{s:4:"type";s:3:"int";s:4:"size";s:3:"big";s:8:"not null";b:1;}s:6:"ip_ref";a:3:{s:4:"type";s:3:"int";s:4:"size";s:3:"big";s:8:"not null";b:1;}s:12:"country_code";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:3;s:8:"not null";b:1;}s:6:"region";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:3;s:8:"not null";b:0;}s:4:"city";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:128;s:8:"not null";b:0;}s:3:"zip";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:8;s:8:"not null";b:0;}s:8:"latitude";a:3:{s:4:"type";s:5:"float";s:4:"size";s:3:"big";s:8:"not null";b:1;}s:9:"longitude";a:3:{s:4:"type";s:5:"float";s:4:"size";s:3:"big";s:8:"not null";b:1;}}

I currently have two Services configured. One is drupalgap and the other is my own custom for specialized queries and API needs. I've tried enabling / disabling a variety of resources in both my Service endpoints. Both have session authentication enabled, use a REST server, return json formats, and include a variety of resources including all of those user system, drupalgap_user, and user.

What should i do about this missing 'services_user' table?


texts: I am trying to assign a workflow to my custom content type, but i can't find the option to get this working. Is it a bug or maybe just not part of the workflow module?


texts:
I'm trying to run a jquery script for my Drupal 8 site, but in the error console, I get a TypeError: $ is not a function. I know this usually happens when jQuery isn't loaded, but the jquery.min.js is loaded fine. Is it loaded too late? Do I perhaps need a wrapper?

In my theme.libraries.yml, I have the following:

global-styling:
  version: 1.x
  css:
    theme:
      css/style.css: {}
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

My script is simply

$('#some-element').on('click', function() {
  // Do something
}

I would think this is all I need, or am I overlooking something?

Edit:

I don't think this is a duplicate question since:

This is Drupal 8
The dependency is defined in the libraries file. I would think this would take care of exactly the problem described in the other question.


texts: Defining a Complex Sort (by stripping out a pre-defined set of words) with Views

texts:
I'd like to do a more complex sorting on my Drupal 7 View. Specifically, I'd like to sort by a particular field alphabetically (easy - that's the default). However, before the View sorts the field I want it to strip out (a predefined) set of words at the beginning of the field (if they exist) such as the word 'the' or 'a' and sort based on the words that follow.

Does anyone know if this is possible?

My workaround will be to just create a 'sort by' field in the content type.


texts: Text copied into body shows up in edit but not in view

texts:
When I type out text by hand into the body of an "article" it shows up correctly in preview and all views.

If I copy text from some other source like a word doc, HTML doc, even a .txt file; everything after the first line break is not showing up. I've tried reformatting the text, moving it to different programs, changing the "text format", editing it in source view and no matter what I do it won't show up in either preview or saved/published.

Is there some known issue with hidden characters copying over and causing issues?  Or is this some weird Drupal 8 bug?

I'm running core 8.0.2.


texts:
For a couple of last days I've read dozens of articles about Zen 5, its grid system and responsive design. But there are still some questions need to be answered or maybe confirmed.

1. responsive-sidebars.scss file

Let's say I want to have different text color of main content for different media queries. I guess the overall definition of the color should be in pages.scss file, but for specific media queries it should to be in responsive-sidebars.scss, right? A've added a color: red; syntax to the example shown in the second question. Is this correct place for this property and value?

2. Override $zen-column-count variable

Let's assume that I want a scenario like this. For the front page I want to have 5 column grid at @media all and (min-width: 960px). But for non-front pages I want to use 10 column grid at the same media query. I reckon, I can do it like this:

@media all and (min-width: 960px) {
 $zen-column-count: 5;

 .sidebar-first {
  #content {
   @include zen-grid-item(4, 2);
   color: red;
  }

  .region-sidebar-first {
   @include zen-grid-item(1, 1);
  }

 /* not-front pages */
 $zen-column-count: 10;

 .not-front .sidebar-first {
  #content {
   @include zen-grid-item(7, 3);
  }

  .region-sidebar-first {
   @include zen-grid-item(3, 1);
  }

 }
}

3.Different max-width query for front and non-front pages.

Let's say I want to have different max-width query for front and not-front pages. In the responsive-sidebars.scss file I found this notation:

@media all and (max-width: 1125px) {

}

While the only difference between front and non-front pages is a body class, how can I prevent this to use it only for front page? Is the notation of ".front" class is enough to apply this media query to front page?


texts:
I have created 3 custom blocks in /admin/structure/block/block-content and I am trying to export them from admin/config/development/configuration/single/export. There isn't any option to achieve this. I am able to export fields and field storage, but not blocks and their content.

How can I export a block created in a custom block library?


texts: How do i select all from database and do while loop with them

texts:
I did this easy select and im getting Error: Call to a member function fetchAssoc() on boolean , im beginner, im just trying to pull out two variables and make operations with them.

$result = db_select('cities', 'c')
        ->fields('c')
        ->execute()
        ->fetchAssoc();

  while ($row = $result->fetchAssoc()) {

    $city_id = $row['city_id'];
  $city_name = $row['city_name'];

Only this is working for me

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

  while ($row = $result->fetchAssoc()) {

    $city_id = $row['city_id'];
  $city_name = $row['city_name'];


texts: Search_api_solr: SolrException undefined field ss_type

texts:
I am configuring search api and apache solr on my localhost. But it gives me the following error

  An error occurred while trying to search with Solr: "400" Status: Bad Request: Bad Request{"responseHeader":{"status":400,"QTime":1,"params":{"hl.fragsize":"0","f.spell.hl.snippets":"3","hl.mergeContiguous":"true","qf":["tm_title^5.0","tm_body$value^1.0"],"hl.simple.pre":"[HIGHLIGHT]","f.spell.hl.fragsize":"70","json.nl":"map","hl.fl":"","wt":"json","hl":"true","rows":"10","fl":",score","hl.snippets":"1","start":"0","q":"\"test\"","hl.simple.post":"[/HIGHLIGHT]","fq":["((ss_type:\"article\") OR (ss_type:\"page\"))","index_id:default_node_index"]}},"error":{"msg":"undefined field ss_type","code":400}} .

on the site. The same error displays when I try to view the default node index.

And on the apache solr configuration page it displays the following error in logging.

  org.apache.solr.common.SolrException: undefined field ss_type

I am using apachesolr 4.6 version.

EDIT

I have created the new server and when view that server at the top of the page this error displays;

  You are using an incompatible schema.xml configuration file. Please follow the instructions in the INSTALL.txt file for setting up Solr.


texts: preprocess function call - $vars[node_title] does not work as a parameter, while $vars['node-title'] does

texts:
I am writing a preprocess function. I provided a linkIt function that does the linking for me:

function linkIt($what, $where) {

return '' . t($what) . '';

}
If I call it this way:

$test= linkIt('XXX', $vars[node_url]);

it produces a Drupal error 'Use of undefined constant node_url - assumed 'node_url''. If I call it

$test= linkIt('XXX', $vars['node_url']);

with quotes around node_urlit works fine.
The former syntax is properly evaluated if I do not pass it as a function paramter, for example in

$vars['opis'] = '' . t('XXX') . ''

Why is it so?


texts: how to insert the See All link in a drupal view block

texts:
i created a  News block that display only 3 lasted news, and i want create a button "See All News"
how i can do it ?


texts:
I am using CKEditor and I want ,when creating a new node, in the textarea of CKEditor to add some default text every time a user tries to create a new node.
How can I do that?
thanks


texts: It is possible to revert a single item of the component programmatically?

texts:
I've feature module which have thousands of entries and I'd like to investigate which item is taking the longest time.

Currently all my features takes over 5h to revert, and I assume it's mainly because of rules config components which there are over 700 (10-20sec each rule, so it's like 2-3h for rules alone) in a single module, and over 200 exported entityforms (which also is slow). This is already after fixes, because before it was taking over 8-10h (before the MySQL stopped with gone away error), but this was due to the bug with infinite loop (some Entity+Rules conflict), so disabling entity_rebuild_on_flush variable at least worked in terms of finishing the process. This is especially trouble when you're reverting your features during each deployment or building your local environment on daily basis which takes 5h.

So my plan is to revert only rules which I need (e.g. via hook_update).

I'm aware that you can use features_revert to revert a single component:

features_revert(array('module' => array('component')));

however it takes forever and I would like to know if it is possible to revert only single entry (e.g. foo_my_rule_x) of a component (e.g. rules_config), in other words - a single line of feature module, for example:

features[rules_config][] = foo_my_rule_x

and not anything else, using a standalone code or drush.


texts: Extracting user field values from dynamic SQL queries

texts:
Aim
I have successfully written a fairly long dynamic sql query, however am struggling with a seemingly simple part at the end.
Although, I am able to successfully extract mail and name from the users table, when I try to extract field_first_name it returns the error below.
The users table has a column with the machine name: field_first_name
Code
    $database = \Drupal::service('database');

    $select = $database->select('flagging', 'f');
    $select->fields('f', array('uid', 'entity_id'));
    $select->leftJoin('node__field_start_datetime', 'nfds', 'nfds.entity_id = f.entity_id');
    $select->fields('nfds', array('field_start_datetime_value'));
    $select->leftJoin('node_field_data', 'nfd', 'nfd.nid = f.entity_id');
    $select->fields('nfd', array('title'));
    $select->leftJoin('users_field_data', 'ufd', 'ufd.uid = f.uid');
    // TODO extract first name
    $select->fields('ufd', ['mail', 'name', 'field_first_name']);

    $executed = $select->execute();
    $results = $executed->fetchAll(\PDO::FETCH_ASSOC);

    $username = $result['name'];
    $email = $result['mail'];
    $first_name = $result['field_first_name'];

Error
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ufd.field_first_name' in 'field list': SELECT f.uid AS uid, f.entity_id AS entity_id, nfds.field_start_datetime_value AS field_start_datetime_value, nfd.title AS title, ufd.mail AS mail, ufd.name AS name, ufd.field_first_name AS field_first_name FROM {flagging} f LEFT OUTER JOIN {node__field_start_datetime} nfds ON nfds.entity_id = f.entity_id LEFT OUTER JOIN {node_field_data} nfd ON nfd.nid = f.entity_id LEFT OUTER JOIN {users_field_data} ufd ON ufd.uid = f.uid; Array ( ) in event_notification_cron() (line 63 of /app/modules/custom/event_notification/event_notification.module).

Field


texts: token value not show in webform submission page

texts:
I put following submission message in my webform

  Your applicantion id is %value[application_id]
  your ip is %ip_address

when submitting the form, the token values didn't showup in submission message. The submission message just shown the same as

  Your applicantion id is %value[application_id]
  your ip is %ip_address


texts: How to set up multiple hierarchy taxonomy?

texts:
I am struggling to find the solution for the following situation: I am building a tourism site with POIs as nodes (Drupal 7). The POIs are categorized/tagged in a State-County-City hierarchical vocabulary. I want to add two another cathegories - Historical region and Tourism region. Each City belongs to exactly one historical region and one tourism region and these regions do not cover the same area (meaning that e.g. two cities belong to the same county, but to different historical and tourism regions). While creating new node/POI the user/editor selects the State-County-City via Simple Hierarchical Select module (this structure is generally well-known) and I want to automatically assign the corresponding Historical and Tourism region to the node, based on the City selected (as the division into Historical and Tourism regions is not obvious for the general userbase, but I have the corresponding database available).

How to generate the relationship between the terms for Cities in the State-County-City vocabulary with the corresponding Historical and Tourism regions, while maintaining the possibility to list all nodes/POIs in a State/County/City/Historical region/Tourism region?

I have thought about having two additional vocabularies but failed to find a way to connect them with the City terms in the first. I also thought about having multiple parent terms in one vocabulary for the Cities - but this messes up the vocabulary (and Simple Hierarchical Select) completely and is therefore inapplicable. Any help appreciated.


texts:
Drupal 7.38
Organic Groups
Drupal Commerce
Commerce Node Checkout

I have everything setup and working well.  There's one strange bug.  On checkout, I have Title displayed so the logged in user can create a new group, but URL alias also shows up.  I don't want this.  I have pathauto handling all this automatically.  Screen shot attached.  I've dug through all display settings.  I'm lost.  Any help would be appreciated.  Screen shot below.

Thanks


texts: White Screen of Death, From Apache to Litespeed

texts:
I'm facing a White Screen of Death on some backend(admin) pages after migrating to a new server. Apache--->LiteSpeed. New domain. When I migrate to a different server running Apache I don't have any issues.

I get WSOD when I click "Flush all caches" or after enabling a module.

The link to configure AWS for PHP module is missing from the admin menu.

Recent logs messages:

page not found   2013-08-01 18:19    build/mediaelement-and-player.min.js
page not found   2013-08-01 18:20    favicon.ico

May you help?


texts:
I'm very new to Drupal so I hope you'll forgive the silly question: where is the server-side code for my AJAX call?

I've read the documentation on the Ajax Framework, but I can't find any instances of #ajax or callback in my code.

Capturing the /system/ajax request yields some interesting form variables:

form_build_id: form-cBW24WCJRFxgW5TMHSa-9hQ_tVenToYkx2ObzTgnQKM
form_id: commerce_checkout_form_ip_info
_triggering_element_name: ief-36484c27df589bd88b009b3e91d079f24f9559cc-add
_triggering_element_value: %2B+ADD+MEMBER

(There are lots of others, but those seem like the relevant ones.)  I gather that this is a form using the Commerce module, but that doesn't help me much.

Finally, here's the line of code setting up the value of the button that triggers the AJAX call:

$form['customer_profile_ip_info']['field_company_ip_customer_info']['und']['actions']['ief_add']['#value'] = "+ ADD MEMBER";

Hopefully this is enough information to determine what's happening here.


texts:
I need to know how to migrate my Drupal 6 database from MySQL to PostgreSQL. I also like to hear first hand experience tales about actual migrations.

P.S. I found this drupal-mysql2pgsql.pl migration script which apparently does the job but I could not make use of it due to the fact that I dont' know how to make " passwordless account in both databases". There is also this guide (in Thai) which adds credentials to database connection lines in the script. But it did not help either, as I could not connect to Postgresql. I know very little about Postgresql and may have had some silly mistake. Any through explanation/tutorial on this would be much appreciated.


texts: Comments only showing subject, no comment

texts:
Using Drupal 7 with a custom made theme, the comments are only showing Subjects, and ignoring the comment body.

In my comment.tpl.php file I have:

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
<?php print $picture ?>

<?php if ($new): ?>
<?php print $new ?>
<?php endif; ?>

<?php print render($title_prefix); ?>
<h3<?php print $title_attributes; ?>><?php print $title ?>

<?php print render($title_suffix); ?>

<?php //print $permalink; ?>
<?php print $submitted; ?>

<div class="content"<?php print $content_attributes; ?>>
<?php
  // We hide the comments and links now so that we can render them later.
  hide($content['links']);
  print render($content);

?>
<?php if ($signature): ?>

  <?php print $signature ?>

<?php endif; ?>

Any ideas on how to get the comment to show?


texts:
I am using the Rules module to create some default group content upon creation of an organic group. The rule is copied below and works well except that the url pattern for the default content is not being generated as I want it to be.

I would like url pattern to be [node:og-group-ref]/content/[node:title] and I have this working for regular group content which is created manually once a group exists.

The problem is that default content created by rules is missing [node:og-group-ref] in the url. If I edit the generated content I see that the setting to 'Generate automatic URL alias' is unchecked. If I then enable this and re-save the url ends up as I need it.

And I am guessing that pathauto is not aware of the og-group-ref value when the node is first created by rules and can not use this token.

I have tried including an action to create a url in the rule, but this seems to get overriden by pathauto.

So my question is - How to set the url alias of a node created by Rules?

{ "rules_og_create_group_content_timetable" : {
"LABEL" : "OG Create group content - Timetable",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "og" ],
"ON" : { "node_insert--og_group" : { "bundle" : "og_group" } },
"DO" : [
  { "entity_fetch" : {
      "USING" : { "type" : "node", "id" : [ "node:nid" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "og_page",
        "param_title" : "[entity-fetched:title] Timetable",
        "param_author" : [ "node:author" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created__page_stub" : "Created entity page stub" } }
    }
  },
  { "entity_save" : { "data" : [ "entity-created--page-stub" ], "immediate" : "1" } },
  { "og_group_content_add" : {
      "entity" : [ "entity-created--page-stub" ],
      "group" : [ "entity-fetched" ]
    }
  }
]

}
}


texts: Query params in url does not appears in node url after updating

texts:
I need to append node path programmatically to make the url look like [the link]?utm_source=Home%20Page&utm_medium=website&utm_campaign=AB%20Test&utm_content=Headline A

I'm updating node via node_save()

$alias = drupal_get_path_alias('node/' . $node->nid);
$queryA = array(

          'utm_source'=>'Home Page',
          'utm_medium'=>'website',
          'utm_campaign'=>'AB Test',
          'utm_content'=>'HeadlineA'
        );

$node->path = array(
    'alias' => $alias,
    'query' => $queryA,
    'pathauto' => FALSE,
    'absolute' => TRUE);

node_save($node);

but unfortunately i'm not getting the desired result. Any thoughts how do i do it. do i need append alias?
dpr information for the node path looks like this

Array
(
    [alias] => content/esse-iaceo-lenis
    [query] => Array
        (
            [utm_source] => Home Page
            [utm_medium] => website
            [utm_campaign] => AB Test
            [utm_content] => HeadlineA
        )

    [pathauto] =>
    [absolute] => 1
)

I got another solution and have used conditional views module so that absolutely covered my needs . Drupal power!!!


texts: Display current node rank from votes (voting api) in view

texts:
As in Title. I am struggling by programming but with no luck. Mechanism of voting api is too complicated for me. How can I display current node rank (order number) by votes?

My view now:

Sort critera:
(Vote results) Vote results: Function desc

Relationships
Node: Vote results

When displaying all results it's have order number thanks to view php field module.

Display position in rank of current, single node is hell for me. Custom sql query doesn't work at all.

I am using voting api and rate module.

Please help.

EDIT

Since I am using +1/-1 I try to:

Sum +1 Votes
Sum -1 Votes
Subtract sum of -1 votes from sum of +1

Code:

$plus_rates = db_query("SELECT count(value) AS sum, content_id AS nid FROM votingapi_vote WHERE tag = 'vote' AND value_type = 'points' AND value = 1 GROUP BY content_id ORDER BY sum DESC, nid ASC");
                                         $minus_rates = db_query("SELECT count(value) AS sum, content_id AS nid FROM votingapi_vote WHERE tag = 'vote' AND value_type = 'points' AND value = -1 GROUP BY content_id ORDER BY sum DESC, nid ASC");

                     $pluses = array();
                                         $minuses = array();

                     while ( $row = db_fetch_object($plus_rates) ) {

                                            $pluses[$row->nid] = $row->sum;

                     }

                                         $plus_rates = NULL;

                                         while ( $row = db_fetch_object( $minus_rates ) ) {

                                            $minuses[$row->nid] = $row->sum;

                                         }

                                         $minus_rates = NULL;

                                         $keys = array_keys($minuses);

                                         foreach($keys as $k) {

                                                if (array_key_exists($k, $pluses)) {

                                                        $pluses[$k] = $pluses[$k] - $minuses[$k];

                                                }

                                         }

                                         arsort($pluses, SORT_NUMERIC);

                                         firep($pluses, 'pluses');

$pluses is sorted DESC but order is totally different from my view display:

Sort cirteria: (Vote results) Vote results: Function desc)
Relationship Node: Vote results, Aggregation function: total score

EDIT 2

I try to query votingapi_cache directly but still order is totally different than in views:

  SELECT value, content_id FROM votingapi_cache WHERE value_type =
  'points' AND tag = 'vote' AND FUNCTION = 'sum' ORDER BY value DESC
  LIMIT 0 , 30


texts: Drupal 7 Simple Ajax Module returning 404

texts:
I am trying to do a simple Ajax call in drupal 7.
But i get a 404 not found.
I tried with another drupal install and it worked.

Here is the list of the installed modules :

CKEDITOR,
ctools,
entity,
field_collection,
field_group,
pathauto,
references,
token,
wysiwyg

And here is the code :

function bookmark_ajax_menu() {

  $items['ajax-bookmark'] = array(
    'page callback' => 'bookmark_ajax_add_article',
    'access callback' => 'user_access',
    'type' => MENU_CALLBACK,

  );

  return $items;
}

/**
 *
 * AJAX FUNCTION FOR ADD ARTICLE
 */

function bookmark_ajax_add_article(){
   global $user;
           $user_name = $user->name;

   drupal_json_output($user_name);

}

function bookmark_ajax_init(){
    drupal_add_library('system','drupal.ajax');
    drupal_add_js(drupal_get_path('module', 'bookmark_ajax') . '/bookmark_ajax.js', array('scope' => 'footer'));
}

(function ($) {
  Drupal.behaviors.bookmark_ajax = {
    attach:function (context) {

      // If the site name is present set it to the username.
      $('document').ready(function(){
           $('body').load(Drupal.settings.basePath+'ajax-bookmark');
      });

    }
  };
})(jQuery);


texts: Overriding an entity add/edit form through alterroute

texts:
I want to create my own version of the add/edit form for an entity defined in contrib module (drupal_commerce). I assumed i'd be able to adapt the example here http://www.foreach.be/blog/how-manipulate-forms-drupal-8 to alter route for entity forms. However i am getting the following when i try to load edit

  Fatal error: Call to a member function getEntityTypeId() on a non-object in C:\xampp\htdocs\tocyn\core\lib\Drupal\Core\Entity\EntityForm.php on line 82

My route subscriber looks like:

    if ($route = $collection->get('entity.commerce_product.edit_form') ) {
        $defs = $route->getDefaults();
        $route->setDefault('_form', '\Drupal\mymod\Form\EventForm');
    }

And my new form:

class EventForm extends Drupal\commerce_product\Form\ProductForm
{
   public function buildForm(array $form, FormStateInterface $form_state)
   {

      // doing nothing much here
      return $form;
   }
}

Do i need to do something with _entity_form also??
Grateful for any feedback
Mathew


texts: How to suppress "page not found" messages in watchdog

texts: The issue Add an option to suppress page not found watchdog messages at https://www.drupal.org/node/2836458 indicates that a setting was added to Drupal 8 to suppress page not found errors in watchdog. I can't find the setting in the interface. Am I mistaken in understanding that it was added? If not, where do I find this setting? Running Drupal 8.8.1.


texts: Add JavaScript files to the administrative pages

texts: How do I add JavaScript/CSS files in every administration pages, using a module?


texts:
The following code:

$report .= '
' . t('%percentage of '.$node_type_get_types[$type]->name.' completed.', array('%percentage' => $percentage)) . ' ' . $count . '
';

is inside of iteration, because I need to make the same calculations and collect all the results and output all in one string.

Drupal.org's automated testing complains about the above part:

Concatenating translatable strings is not allowed, use placeholders instead and only one string literal

I don't have any idea how to make this correct.


texts:
What's the preferred way to get the current Node ID while inside a Drupal module function, without passing it in?

Adding more text, because StackOverflow won't post short questions:

Ideally, I'd like some kind of reflection function, where I can simply request the NID of the  node being served in the stack trace. Since Drupal revolves around serving nodes, it stands to reason that there should be some kind of reflection function that makes "the node I'm operating on presently, or NULL if I'm not operating on a node", available at all times.

The best discussions I've found pull the NID out of the URL. This strikes me as a backwards way of recovering the NID, and fragile, to put it mildly.


texts: Why I cannot export vocabulary terms via Features?

texts:
Ok, I've installed features, uuid, uuid_features.

According to docs vocab terms shouls be exported too when creating taxonomy feature.

So I run a command:

  drush fe my_feature taxonomy:tags

but every time inside feature there is no such thing like terms. Only vocabulary is exported. What I am doing wrong?

From code review I see that only hook_taxonomy_default_vocabularies is implemented.


texts: $form_state for an autocomplete callback

texts:
I'm trying to get the value of $form_state for my autocomplete textfield.

Basically, I have a search textfield and checkboxes to restrict the autocomplete.  What would be the best way of passing the checkbox values to the autocomplete?


texts: I split 2 columns my contetnt node with Display Suite and add custom class to the columns. (with Bootsrap responsive class col-sm-3) But display suite still render column with old style: group-left and group right. How can i remove old style?


texts: How can I save an unpublished node skipping required fields validation?

texts:
What is the best way to save node without the required field values?
It would be something like "save as unpublished" and the required validation is omitted, but I am not sure in which module I can find this functionality and how to set it up.


texts: Create custom form button that does not submit webform

texts:
I have webform created via Webform UI, and it's multi-step webform.

In second step ('personal information') I add custom button using HOOK_form_alter with following code

'generate_pdf' => [
    '#type' => 'submit',
    '#value' => t('Generate PDF'),
    '#limit_validation_errors' => [],
    '#submit' => ['generate_pdf_template'],
]

function generate_pdf_template takes values from $form, $form_state inserts them into twig templat, creates PDF and automatically downloads it.

My issue is, that this generate_pdf button submits the form and user is not able to send form via original submit button. Can I somehow prevent submission when generate_pdf is clicked so user can download PDF and still be able to send webform with original button and webform's handlers.


texts:
I am using apachesolr on my drupal 6 website for search. Now I wanted to use filter results by content type on search page.
At first I was using a panel page as search page. Here I tried to use the apachesolr filter by content type block. But this didnt work. I tried all other facets available with apachesolr module and all others worked fine. Now I thought maybe filter by content type doesnt work with panels quiet well so i removed the panel page and used the apachesolr default search psge. Still it doesnt work for me.

Can someone tell me some method for grouping my search results by content type.


texts:
I'm developing a panopoly App for Services and case studies. I have added my required field and created the content type, added panels and views etc. Finally I created the feature and downloaded for the same. I have done this from the following Documentation. Creating Panopoly Apps. http://drupal.org/node/1704334

I have achieved step 1-4 and I am stuck on step 5 : Integrate the feature with Apps.

Please help to create the feature as an App. I don't have any server setup.

Thanks in advance.


texts: Only display content that belongs to User in admin/content

texts:
I have a role called Content Editor and 2 users Chang and Liang with that same role.

They can both add/edit their own content. The role permission is set in such a way that they can only edit own content.

However, when Chang navigates to /admin/content, this user can see all the contents written by all the users.

How to restrict Chang so that he can see only the contents he has written when visiting the /admin/content link?


texts: Why Content Path cannot be used to sort a view?

texts:
Using Views with Drupal 7, how can I use the content path to sort a result table?

I have node title, created date and path as fields for a view.
The first two fields have the checkbox to make them sorting options in the display settings, but the node path field doesn't.


texts:
I am connecting to two sites via SSH

I used Drush 4.4 export on a D6 site to export a node type.

I now want to import that onto a D7 site (running Commerce Kickstart2) which contains a newer version of Drush (if that matters) and I get the above error.

I have no alias or rc file on either the old or new site. However I haven't really needed them as all other commands seem to work. I run Status on the new site and it seems to work:

Drupal version         :  7.28
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  test_commerc
 Database name          :  test_commerce
 Default theme          :  garland
 Administration theme   :  garland
 PHP configuration      :  /home/test_site/php.ini
 PHP OS                 :  Linux
 Drush version          :  6.0-dev
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /home/test_site1/public_html
 Site path              :  sites/default
 File directory path    :  sites/default/files

The errors are:

The drush command 'import' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions.                    [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database setup by
specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See http://drupal.org/node/1428638
for details.

I did run drush cache-clear drush.

I am using a jailshell but this doesn't make sense to me because I can use SQL-CLI for various queries.

What am I missing?

TIA,


texts: Delete node: Remove header, footer and rightbar in delete node page

texts:
I want to remove the header, footer and rightbar in a delete node page (node/.../delete). How can this be reached?

I already tried editing page--node--delete.tpl.php, but this does not work.


texts: How can I create Rules condition for event when 404 error generated?

texts:
I've assigned page for 404 error handling (example.com/404).
I've created Rules condition: Data to compare: [site:current-page:url], Data value: 404.
And I've created some Rules action for this case.

But when I open nonexistent page (example.com/wrong) - there is no corresponding Rules action.
It is because I see 'example.com/wrong' address instead of 'example.com/404'

But how can I create Rules condition for event when 404 error generated?


texts: How to add exist taxonomy term field to custom form

texts:
It's possible to add exists taxonomy reference field to new custom form?

For example: i have a term field named "field_tags" and would like to add to new form ->

  $form['node_taxonomy_term'] = // load here exists taxonomy autocomplete field "field_tags"
  $form['#submit'][] = 'save_node_terms';
  return $form;


texts:
What I want is whenever a registered user saves a page type node - that specific node should be made inaccessible to the user.

So if a registered user has save node/122, node/122 should be made inaccessible to the user.

How can I do it?


texts: Should I log the user out after calling an API using the Services module?

texts:
I am using Services 3.X to make API calls in my Drupal installation.  In order to update a user I:

Make an API call to log in with an account which has rights to modify users (I'm using an admin account)
Using the session I received from step 2, I make another API call to modify a user.

That works.  My question is, should I have a step 3 and log out the account I used in step 1?  The logout, of course will be done via the Services API.  Would there be any bad side effects of not logging the account out?

Thanks.


texts: there are different content types and associated with different taxonomies. for example forum content type associated forum taxonomy, article content type is associated with tag taxonomy and gallery content type is associated with gallery taxonomy. i want to show related contents in front page blog, but taxonomies different. how can i associate them? with using only one taxonomy for all content types or else?


texts: Using Test Mail Collector to avoid sending emails to users during testing

texts:
This page offers some documentation on how to avoid sending emails to actual users during testing or in test environments:

https://www.drupal.org/docs/develop/local-server-setup/managing-mail-handling-for-development-or-testing

The simplest way appears to be modifying your settings.local.php:

$config['system.mail']['interface']['default'] = 'test_mail_collector';

If you use drush, you can then check the emails sent by running:
drush sget system.test_mail_collector

However after adding that line to my settings.local.php, I still received the actual emails. They were not "collected".

In looking at the source code in Drupal\Core\Mail\Plugin\Mail\TestMailCollector.php line 24

 $captured_emails = \Drupal::state()->get('system.test_mail_collector') ?: [];

It seems to me that the correct syntax for setting the test mail collector would be

$config['system.test_mail_collector'] = TRUE;

But that didn't work either.

I haven't been able to find documentation that helps me reverse-engineer the setting based on the retrievable of the state variable.


texts: Superfish module seems to "Ignore" it's very own library

texts:
I have a problem connecting the Superfish library to the module... I've tried to Google this issue and the error I got, but found no direct solution. Here are more details:

I've installed the module alright but when I go to admin/config/user-interface/superfish, it asks me for the library path. I've tried many variations such as:

/public_html/sitesname.com/sites/all/libraries/Superfish
/public_html/sitesname.com/sites/all/libraries/
sitesname.com/sites/all/libraries/Superfish/
sitesname.com/sites/all/libraries/
public_html/sitesname.com/sites/all/libraries/Superfish
public_html/sitesname.com/sites/all/libraries
/public_html/sitesname.com/sites/all/libraries/Superfish/superfish.js

Nothing seems to work and I keep getting the (kinda wired) error "File not found". Any ideas?


texts: Validation of required entity reference field (putting in text that doesn't match anything passes validation)

texts:
Note: I have some more work to do to work out what the actual cause of this issue is.  I can't expect anyone to help me debug it until I've done that, but I don't have time to look into it further just yet.

I have a couple of cases where I have an entity reference field, that is set to required, but when a user fills in some text that doesn't match anything, it passes validation and the node is saved with nothing in that field.

This seems like an identical question to Autocomplete entity reference - Required to select entity except that the accepted answer there doesn't apply in my situation.  I have the autocomplete widget selected not Autocomplete tags style, but you are still allowed to enter text that doesn't match, and save without error.  The end result is that nothing is entered in that required field.

I have these modules installed and actively working on this field: multiple_fields_remove_button references_dialog.  Autocomplete matching is set to contains, and entity selection comes through views.


texts: How to disable picture button after click?

texts:
I'm new at Drupal CMS and programming at all, but I'm trying to find my way to solve this problem.Unfortunately unsuccesful for now.
I've installed Drupal 7.5 and Multipurpose theme which has social icons to redirect to facebook,twitter and etc.In theme settings there is an option to paste link with profile.I wanted to tweak their function a bit but I'm stuck with the code int the page.tpl.php file.
What I'm trying to do is basicly to check if the user is logged in, and if he is and a link was given in the setting of the theme to redirect to the social profile.The problem occurs when the user presses the button twice or more because the link copies over and over instead of refresh...for example: 1 click: https://www.facebook.com/user and on the 2 click becomes: https://www.facebook.com/user/user and so on.
The code:

 <?php if (!$logged_in) : ?>
      <?php if ($twitter_url): ?>

        <a title="<?php print $site_name; ?> in Twitter" href="<?php print $twitter_url; ?>"><img alt="Twitter" src="<?php print base_path() . drupal_get_path('theme', 'multipurpose') . '/images/social/twitter.png'; ?>">  <?php endif; ?>

<?php endif; ?>

So the question is how can I disable the button(become inactive not hidden) after one click or is there any other approach to solve this problem?
Thank you!


texts: Using Form API with AHAH: values don't update correctly

texts:
Here is an example of how I made my AHAH fields in my form:

A textfield:

$form['info']['number'] = array(
        '#type' => 'textfield',
        '#title' => 'Number of people',
        '#weight' => 3,
        '#required' => TRUE,
        '#maxlength' => 6,
        '#prefix' => '
',
        '#parents' => array('info','number'),
        '#suffix' => '
',
        '#size' => 20,
        '#ahah' => array(
                'event' => 'blur',
                'path' => ahah_helper_path(array('info','number')),
                'wrapper' => 'number',
                'method' => 'replace',
                'effect' => 'none',
                'progress' => array (
                        'message' => $form_state['storage']['info']['number'],
                ),
        ),
        '#default_value' => $number,
);

And a select field for time:

    $form['choices']['time'] = array(
        '#type' => 'select',
        '#prefix' => '
',
        '#suffix' => '
',
        '#options' => array (
                0 => 'What time do you want to go?',
                1 => '07.00',
                2 => '07.15',
                ..
                64 => '22.45',
                65 => '23.00',
        ),
        '#weight' => 10,
        '#parents' => array('choices','time'),
        '#ahah' => array(
            'path' => ahah_helper_path(array('choices','time')),
            'wrapper' => 'time',
            'effect' => 'none',
            'method' => 'replace',
            'progress' => array (
                        'message' => $form_state['storage']['choices']['time'],
                ),
            ),
        '#default_value' => $time,
);

The way my form works is that the person fills in the number of people on the trip, and then selects a time. These two fields will trigger a third field made like the textfield above, which displays a price I grabbed from the database. There are 6 possible trips, so in the total (another textfield) all 6 of those will be added together for the price.

Here's the thing: The way my logic is written above, I can see that my prices are being passed to the total. I can see them in the POST and in the JSON response. They are in fact there. BUT the form itself does not display the values! The $cost and $total fields are still 1, even though I can that the price is passing correctly in the code itself. What happened? Does this have to do with $form_state or something else? Any pointers would be greatly appreciated.


texts: Is there a way to send an email to a mailchimp list on the event of a content type being published?

texts:
The title says it all, really.

I want to trigger the dispatch of an email to a list of subscribers on mailchimp every time a certain content type is published.

Using rules I can see that the only mailchimp action available is to sign a user up to a list, so if there is a way of adding a new action to send an email to all users in a list that would be exactly what I need.

Any other methods are welcome too.

Thanks very much.


texts:
I am using node gallery for image gallery of 30 iamges, when i click the image in gallery it will takes to  nodegalleryJcariusel view and display all 30 images with previous and next arrows.

But when i filter the gallery with taxonomy ( will get 10 images) and when i click the image again jcarousel view showing all  30 images of gallery instead of 10 filetered images.

i am not drupal expert, have limited knowledge in PHP, please advice me how to do get only filtered images in jcarousel view.

thnx,
sri


texts:
I am writing a form using the Drupal 7 form API. On submitting the form (via AJAX), the following error is displayed:

  An AJAX HTTP error occurred.
  HTTP Result Code: 500
  Debugging information follows.
  Path: /en/system/ajax
  StatusText: Internal Server Error
  ResponseText: Recoverable fatal error: Argument 1 passed to drupal_array_nested_key_exists() must be an array, null given, called in /drupal7/includes/form.inc on line 1986 and defined in drupal_array_nested_key_exists() (line 6296 of /drupal7/includes/common.inc).

I have two buttons on the form (copy & submit); one is an AJAX call which does some stuff, and the other is used to save the entered data.

This is the code I'm using:

function foo_form ($form, &$form_state, $foo) {
  $form['#foo'] = $foo;
  $form_state['values'] = $foo;

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['copy'] = array(
    '#type' => 'submit',
    '#value' => t('Copy foo'),
    '#limit_validation_errors' => array(),
    '#submit' => array('foo_form_submit'),
    '#ajax' => array(
      'wrapper' => 'foo-form-wrapper',
      'callback' => 'foo_form_callback',
    ),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => (!isset($form_state['values']['name']) ? $foo->name : $form_state['values']['name']),
  );

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

  return $form;
}

function foo_form_callback($form, $form_state) {
  return $form;
}

function foo_form_submit ($form, &$form_state) {
  // Did we use the AJAX Call?
  // @todo: can we check this some other way?
  if (!isset($form_state['triggering_element']['#ajax'])) {

    // We didn't, save the entered values

    $form_state['rebuild'] = false;
    return;
  } else {

    // We did, do some behind the scenes stuff...

    $form_state['rebuild'] = true;
  }
}

Does anyone have an idea of what could be wrong?


texts: How to programmatically truncate table in Drupal8

texts:
I'm wondering how to programmatically truncate a table in drupal8.

Like:

db_truncate('some_table');

Is this possible?


texts: How do you troubleshoot search tracking not working with the Google Analytics module?

texts:
I have a site that uses the Google Analytics module. Analytics is working fine. However, I enabled search tracking in the module -- and updated the query string to search in GA -- but search data is not being tracked. After 72 hours I'm not seeing any search data.

I'm unsure how I can troubleshoot this. I reviewed the JS routine being output on the search page and verified the GA code is appearing, though I don't see anything specifically relating to search (not sure it would output anything different).

How do I go about troubleshooting this?


texts: How to redirect the user using hook_init?

texts:
If the user requests www.mysite.com/user/login he should be redirected to www.mysite.com/mylogin. I know this is possible with hook_init or hook_boot, can some one explain how this can be achieved.

Thanks


texts: How to get more info on error during clone?

texts:
When cloning one of my sites I get the following error:

  SQLSTATE[HY000]: General error: 1267 Illegal mix of collations
  (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for
  operation '='
  - error

I am unsure how to find where this is happening. I would appreciate any help!


texts:
I have a Drupal 6/Ubercart 2 website with a desktop-specific theme. I intend to create a POS/Kiosk theme for the site, to be used when the site is accessed via a tablet (and possibly via smartphone). That theme would be bare-bones... a couple of Views showing products, probably the AJAX cart module, and very little informational pages. The POS concept would involve a kiosk with an ipad that public customers in a retail location would be able to use to place orders right then and there.

I suppose I just want to see if anyone out there has done a setup like this, or whether anyone has any ideas on things to avoid, issues that may be encountered, etc. Ideally, the end result of this port would be a recipe of sorts, that everyone else could use for similar situations.

So far, potential issues I have come up with are:

Must auto-log out users upon successful order completion. Is there a way to do this in Drupal/Ubercart via stock settings or an existing module?
Some type of auto- or manual-logout for when a customer walks away from the POS without completing the order (so that the "next person up" can start with an empty cart, or can at least easily clear the cart and start their own shopping experience). I suppose this can be accomplished with a large "Click here to start a new session" button that would basically be a "rebranded" log out button...
...I'm hoping other viewers of this question might be able to point out any other issues I may not have thoughts of yet.

Looking forward to any input anyone out there may have!


texts:
I know how to hook_alter a Webform build form.
I also know how to validate it using a hook_validate.

Is there a chance to skip a certain Webform page when some validation code results in false?

I cannot find any solution ;-(


texts: Views Data Export module duplicates node titles

texts:
I need to export a content type that has paragraph bundles. I'm using the Views Data Export module (in CSV format) to do the export. I am able to export the content, but not in the correct format. As you can see below (second to last screenshot), the title of the node gets duplicated 7 times, i think it's because there are 7 paragraphs, so is it possible to have all individual node content in one row instead of 8?
Thanks in advance!
Here's the view:

Here i'm calling the relationship of the paragraphs:

Here i'm calling a particular paragraph:

Here I added the paragraphs to the content type as a field:

As you can see, i'm using 7 paragraphs

This is the csv output:

This is how i would like the csv output:


texts: How to deal with deleted posts: Returning 410 status and preventing path re-use

texts:
For my jobs site, I want to return 410 status for those jobs which expire or are removed permanently. How can I do it so that 410 instead of 404 is returned for say job related node types( they'll be unpublished first and later deleted permanently I guess I should return 404 for unpublished then 410 when deleted)?

Secondly in case it really works out to use 410 for such pages but later new job pages may be published by Path Auto which could assign the very same url's based on title name for which 410 was returned once. I understand if a url comes back after 410 it will be permanently ignore by Google. So I guess I'd need that Path Auto always generate a non-duplicated (deleted) url. So solve this I'd need to tag an always increasing number with the url or adds jobs in url directories based on dates like xyz.com/oct/job1.... So I'd need to take care of this too if I'm able to return 410 for such page.


texts:
I know that I can programmatically create a user using the following code, in Drupal 7.

$new_user = array(
  'name' => $name,
  'pass' => $sifra, // note: do not md5 the password
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);

What is the equivalent code in Drupal 8?


texts: Breadcrumbs for a view page with arguments

texts:
How do I set the breadcrumbs for a view page with arguments? I've used the "User: username" argument, and the following PHP Code as default argument, but it doesn't work:

$breadcrumb[] = l('Home', NULL);
$breadcrumb[] .= l('Our Team', 'team');
drupal_set_breadcrumb($breadcrumb);


texts: Rule to send an email on node save printing a field value of a referenced node

texts:
I am using Drupal 7, and the modules References and Rules.

I created two content types: A and B.

A has a field (A:b_nodes) which is multiple node references of B which has field (B:time).

How can I configure a rule so that when A is saved, an email will be sent with body text like the following:

here are the B nodes time data contained in A

B1 : 2 januari 2013
B2 : 5 may 2013
B3 : 15 august 2013


texts: Which backup system is good for my local project?

texts:
I'm using ubuntu, and I accidentally deleted my project last weak. I tried to recover it but no luck.

Which is the best way to backup my project automatically including my Database (my database is Mysql)? What do you recommend?


texts:
we are currently trying to get our drupal commerce 2 attaching a certain shipping method based on the weight of the order. It is pretty simple (at least I thought so): if the order is below 20kg, it is one rate, above a second rate.
Here is what I did:

enabled commerce shipping module and physical fields
added a custom physical weight field field_prod_gewicht to the default product type (the only one we have)
marked the default product variation as shippable
filled the individual products with their weights accordingly
created two shipping methods with different prices, only restricted by Shippment Weight

So far so good - on the shipping page I see indeed only the lower rate shipping method, but if I add more weight to the order, the higher rate shipping method never appears.
My suspicion is, that the weight is not calculated at all, or that there is some kind of implicit convention I did not follow.
Anybody has an idea, how to solve or debug this?
Thx a lot!


texts: How do I populate a webform component with a %_GET variable token?

texts:
I have webform 4 enabled. I just created a textfield component and set its default value to %get[my-key]. But the token is not working at all. I also tried with %_get[my-key] and [%get[my-key]] but is not working neither.

As far as I understand Webform 4 in not working anymore with POST variables in favor of GET variables.

How can I get the GET variables?


texts:
I am looking for a way to manage nodes from command line.

I am aware of drush and drush-entity, and it can do the job in a way, but I thought it could be easier having the nodes stored in files (instead of a database) to version control them with git.

I there a way to do this? (Maybe a module or a drush script)


texts: How do I get Drupal to 'discover' a new layout .tpl?

texts:
I wanted to make a slight variation of a .tpl layout a plugin uses. To do that I simply when into the plugins file structure and duplicated one of its layout folders and renamed the files within (.css, .tpl and .inc). I then made the changes to the .tpl file.

In the .inc file I find:

$plugin = [
  'title' => t('Two Col 50/50'),
  'category' => t('Foundation'),
  'icon' => 'icon.png',
  'theme' => 'foundation_twocol_50_50',
  'admin css' => 'foundation-twocol-50-50.css',
  'regions' => [
    'left' => t('Left'),
    'right' => t('Right'),
  ],
];

All I did here was alter these names slightly to:

   $plugin = [
      'title' => t('Two Col 70/30'),
      'category' => t('Foundation'),
      'icon' => 'icon.png',
      'theme' => 'foundation_twocol_70_30',
      'admin css' => 'foundation-twocol-70-30.css',
      'regions' => [
        'left' => t('Left'),
        'right' => t('Right'),
      ],
    ];

I then refreshed my cache and theme registry, but the new 70/30 option does not appear when I go to swap layout for the mini-panel I'm working on.

Is there something I must do to 'tell' drupal this new layout exists?


texts: What Multiple contributors means in Drupal Translations site?

texts: I just notice that when you go to the different Drupal Translations sites (for example the French site) there is a user named Multiple contributors but I can't figure out what this means, is a user or a contribution that is made from a different site?


texts: Have Google Analytics code still run on force download

texts:
When you click on a download link (my_download/download/agent/%/week/%) that I have set up dynamically for each user it runs some logic and downloads a file.

I was thinking that I could just check Google Analytics to see how many people downloaded the file but the data is not there.  Does anyone have any idea to have it force download like I have set up and run Google Analtyics?

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['my_download/download/agent/%/week/%'] = array(
    'title' => 'Download',
    'description' => 'Download File.',
    'page arguments' => array(3, 5),
    'page callback' => 'my_module_file_download',
  );

  return $items;
}

/**
 * Download file.
 *
 * @param string $agent_id
 *   Agent number.
 * @param string $date
 *   Date string.
 *
 * @return string
 *   Force file to download or give error.
 */
function ea_email_requote_agent_file_download($agent_id, $date) {
  $file_name = my_module_agent_file_name($agent_id, $date);
  $file = "/mypath/$date/$file_name";

  if (file_exists($file)) {
    // Transfer to browser download.
    drupal_add_http_header('Pragma', 'public');
    drupal_add_http_header('Expires', '0');
    drupal_add_http_header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
    drupal_add_http_header('Cache-Control', 'private');
    drupal_add_http_header('Content-Type', 'text/csv');
    drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $file_name . '";');

    readfile($file);
    drupal_exit();
  }
  else {
    drupal_set_message('File has not been loaded yet.', 'error');
    return '';
  }
}


texts: Display ubercart product image given a product nid

texts: How do I display a product's image given the nid?


texts: access the node id of a field collection

texts: How do I access the node id of a d8 field collection that is attached to the node in  hook_preprocess_field(&$variables)?


texts: Using multiple templates in a Drupal 8 module

texts:
I have produced a simple Drupal module which provides a wrapper for a JavaScript library. I'm working on a separate module which will produce several pages of examples of the library and wrapper in action. These pages will each contain a two sections, the library, and description text and miscellaneous HTML.

What is the best technique to do this the Drupal 8 way?  I can imagine two strategies:

Each page will be a separate function within my controller. The function can first add two entries to the output array, the first will contain the data for the library, and the second the raw HTML and text.
In the second technique, I would place all the HTML and text in a twig template. Then I would add all the data for the library in the controller and add a reference to this new theme template as a second entry in the output array. I like the idea of this second strategy, but I don't know how to accomplish it. I've look at code for several Drupal 8 projects and read a few tutorials, and I haven't seen an example of this. The hook_theme function always contains a single return statement. How would I add a switch or if statement within hook_theme to determine which twig template to return.

If there is a third option that is even better, let me know.


texts: Problem with anonymous Flag and webform_select_ options_info() only visible to logged in users

texts:
So I've been trying to implement an anonymous "wish list" for an eCommerce site using webform_select_options and Flag. My implementation uses an anonymous flag set on my products and uses webform_hook_select to add a select list of the flagged products to a webform.

The issue I have is that the webform_select_options only show up in the webform when the user's logged in, thus failing as an anonymous implementation.

UPDATE (number 2 8/12/15)

I can confirm that the items are flagged when an anonymous user flags them. I tested this with a block displaying the flagged items when the site was viewed in incognito mode, the list is modifiable (I can add and remove flagged items), so it behaves more or less the way I expect it to.

The view shows commerce products that have been flagged by the current user. This shows me that the items are flagged. I have tested this with multiple browsers in incognito mode and can confirm that the lists are different for different anonymous users.

I tried the dpm($view->result); and it looks like the function doesn't get called with anonymous users. The function prints results with an authenticated user, but no result with anonymous users. I adjusted anonymous permissions to see devel information and can confirm that the function is called with anonymous viewers but returns an array with 0 objects.

Here is the code I'm using, the flag is defined through the flag module UI.

<?php
 function webform_hook_webform_select_options_info() {
   $items = array();
   if (function_exists('webform_hook_user_flag_sample_requests')) {
     $items['webform_hook_user_flag_sample_requests'] = array(
      'title' => t("Sample Requests (User Flag list)"),
      'options callback' => 'webform_hook_user_flag_sample_requests',
     );
   }
   return $items;
 }
 function webform_hook_user_flag_sample_requests() {
       $view = views_get_view('webform_flag_views', TRUE);
       $view->set_display('webform_options');
       $view->execute();
dpm($view->result);
       $options = array();
       if ($view->result) {
         foreach($view->result as $item) {
        $options[$item->product_id]= $item->commerce_product_title . render($item->field_field_image[0]['rendered']);
          }
           }
       else {
         $options[0] = t("Nothing");
       }
    return $options;
          }

So, I am at a loss at to what is wrong here, or how to approach this problem. I followed the tutorial here http://drupalsteve.com/node/57, but there doesn't seem to be an obvious way to resolve this.

I now strongly suspect that this is related to the general issue of showing a view to an anonymous user. Normally, you'd mitigate this by disabling SQL rewriting. Now, I wonder if my flags aren't showing up because I haven't programmaticaly set the advanced options of the "view" being created in the script.

So, I can think of two options: 1) create the flag array without generating a view; or 2) set the advanced query setting to disable sql rewriting.

thanks in advance.


texts: How to link taxonomy and views in a succinct way?

texts:
So here is my use case: I have taxonomy vocabularies titled accommodation, and in the vocabulary, there are 4 terms.

hotel
motel
campground
guest housing

I want to create a view that displays in a page that has these four terms as menu links that once you click the link all content nodes containing that taxonomy term are listed. I have been struggling with this.

My main Block is creating a menu from taxonomy and linking it to the view(I would like to use a custom URL), I have tried the Taxonomy Menu module, which is close, but cannot figure how to configure it correctly, I have gotten closest creating an attachment display within the view. I am so close.


texts: How to create a custom entityform template used by Print module?

texts: I use Print Module and it is possible to create a custom template for generating pdf with node. But I can't do it with Entityform.


texts:
I was wondering if it's possible to make nodes without path alias not accessible. By this I mean that visiting /node/$nid/ users will not be able to see its content, but if that node has an path alias (e.g. /myarticle/my-article-name/) the node will be visible using the path alias.

Is it possible to achieve it with code?

By researching, I found that I can do this in hook_menu() with either
 $items['node/%node']['page callback'] = 'drupal_not_found'; or $items['node/%node']['access'] = FALSE;.

The problem is that I can't access with /node/$nid/ and without /myarticle/my-article-name/, it raises permission denied.


texts: Add extension .csv to file created with Views Data Export

texts:
To export user data into a csv I've setup a view display of type data export succesfully.
I've setup a path "admin/people/export" and when visiting it will return a file.
The file is a csv file but it's created without the extension .csv.

Is there a way to create this file with this extension?

Thanks in advance


texts: How to show the author as entity reference of a file used in a node?

texts:
I have a content type where images are uploaded / managed with media module. Images have a mandatory entity reference field for the author.  Now i want to show the author always next to the images. I can't get it to work. Last thing i tried was an entity view attachment, which works great if attached to the file itself, but not if attached to the node. I think the problem is the contextual filter. If i use the file-id the view takes the node id and shows the wrong author. If i try the node-id as contextual filter, it doesn't show anything (because the nodes have no author). How do i setup this configuration right?

Any help appreciated! Thanks!


texts: Using Feeds module to import to User_Reference fields?

texts:
I'm been trying to come up with a mechanism to insert/update certain nodes in our Drupal system.  When I try to do the field mapping in Feeds most of the fields are listed and selectable.  But, for those fields which are defined as User_Reference fields, they ARE NOT listed in the target field list.  I can find no other reference to this.

So, how does/can one map a csv field to a user_reference type field defined in a content type?

TIA


texts: How do I alter images being added via IMCE CKEditor plugin?

texts:
I just wanted to share my solution since I did not find any clue or different way of fixing the following problem:

Formerly, you could add a default class/ alter attributes of newly inserted images (or elements) in CKEditor. In Drupal 8, the ckeditor.config.js apparently was removed. Also, images added via IMCE CKEditor plugin are added via insertHTML and there seems not to be any way of manipulate the html string (despite listening to the insertHtml event) with the htmlParser.

How to alter the attributes of images added via imce in ckeditor?


texts: CRUD operations on site from external application

texts:
We have an application behind our firewall that we want to push content to a content type on our external Drupal site. Our internal application will need to create new nodes, update existing nodes, and delete existing nodes as needed. It would also have to have some kind of authentication method that would be used by the application.

What modules/process (services maybe) are best for doing this type of action on the Drupal site?
What type of custom programming will need to be done on the Drupal side to allow this?


texts:
I have an override for my theme called:

corporate_form_element()

The base hook was copied and tweaked. Multiple forms have to be modified and in some cases some individual elements did too. I typically get around this by checking conditionally whether markup is needed.

For instance I check for checkboxes and theme accordingly:

<?php
if($element['#type'] == 'checkbox'){
    return '
' . $output . '
';
}
?>

However now I wish to theme two text fields quite differently than most others in forms and I have discovered there is no way to detect which form the current call is for. I have "hacked" this by adding custom '#fields' in my forms elements (either those I provided explicitly or hooked into via hook_form_alter) and checking for this.

This works but is a horrible hack and not very clear.

What is the preferfed drupal way of achiving this result? Can I overrivde MYTHEME_form_element_FORM_ID or something similar? I know this can be done to MYTHEME_form_alter but what about individual elements????

Alex


texts: My themes breakpoint file isn't being loaded

texts:
For some unknown reason my theme is not loading it's breakpoint yml file, is there anything that could block this from being loaded?

Edit:

Filenames correct if I copy it to another folder it works. Also breakpoints definitely enabled.


texts:
<?php

        //https://www.drupal.org/node/1806758
        function mhzipcode_block_info() {

          $block = array();
          $block['mhzipcode'] = array(
            'info' => t('mhzipcode'),
          );
          return $block;
        }
        /*
        Implement hook_block_view
        */

        function mhzipcode_block_view($delta= ''){
          $block = array();
          switch($delta) {
           case 'mhzipcode' :
             $block['content'] = drupal_get_form('mhzipcode_storage_form');
           break;
          }
          return $block;
        }
        /*
        Implement zipcode_view function
        */

        function mhzipcode_storage_form($form, &$form_state) {
          if ($form_state['rebuild']) {
            $form_state['input'] = array();
          }
          // Initialize
          if (empty($form_state['storage'])) {
            if (empty($form_state['input'])) {
              $_SESSION['constructions'] = 0;
            }
            // Put the initial thing into the storage
            $form_state['storage'] = array(
              'thing' => array(
            'zipcode' => '',
            'phonenumber' => '',
              ),
            );
          }
          // Count how often the form is constructed.
          $_SESSION['constructions']++;
          //drupal_set_message("Your form has been saved.");

          $form['zipcode'] = array(
            '#type' => 'textfield',
            '#title' => 'Zip Code',
            '#size' => 15,
            '#default_value' => $form_state['storage']['thing']['zipcode'],
            '#required' => TRUE,
          );
          $form['phonenumber'] = array(
            '#type' => 'textfield',
            '#size' => 15,
            '#title' => 'Phone Number',
            '#default_value' => $form_state['storage']['thing']['phonenumber'],

          );
           $form['continue_submit'] = array(
            '#type' => 'submit',
            '#value' => 'Continue submit',
            '#submit' => array('mhzipcode_storage_form_submit'),
          );

          if (isset($_REQUEST['cache'])) {
            // Manually activate caching, so we can test that the storage keeps working
            // when it's enabled.
            $form_state['cache'] = TRUE;
          }

          return $form;
        }
        function mhzipcode_storage_form_submit($form, &$form_state) {
          $zipcodeAlias = $form_state['values']['zipcode'];
          $zip_code = db_query("select PhoneNumber from {Phone_number} where Zipcode='".$zipcodeAlias."'")->fetchField();
          die;
          $form_state['storage']['thing']['phonenumber'] = $zip_code;
          $form_state['rebuild'] = TRUE;
        }

Form doesn't submitted and mhzipcode_storage_form_submit isn't working .doesn't load this function code , and die is not load .


texts:
How can I make "home" link on bartik menu uppercase and instead name it "front page"?
I tried by going to edit it at structure-menus-main navigation and i cannot because it says
"This link is provided by the Standard module. The title and path cannot be edited."
I created a subtheme of bartik. What should i write there in order to change it?
Thank you.I am using Drupal8.


texts: hook_ENTITY_TYPE_insert never gets called

texts:
Can anyone help me on the below functions. I am trying to alter user registration form and add my user form fields to default registration form. I am successfully retrieving data till validation, but I am not sure where I am going wrong in hook_user_insert. I am not able to retrieve the field value of my custom fields in hook_user_insert function.

Early support will be helpful in completion of the module.

function security_questions_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Hide the questions form when the user is being registered by an admin.
  if (!\Drupal::currentUser()->hasPermission('administer users')) {
    // Merge in our user form.
    $form += SecurityQuestionsUserForm::buildForm($form, $form_state);
    array_unshift($form['#validate'], 'security_questions_form_user_register_form_validate');
    // We can't add our submit handler here, because the user account doesn't
    // exist yet. Instead, we will get the info during hook_user_insert().
  }
}

/**
 * Validation handler for security_questions_form_user_register_form_alter().
 */
function security_questions_form_user_register_form_validate(array &$form, FormStateInterface $form_state) {
  //module_load_include('inc', 'security_questions', 'security_questions.pages');
  SecurityQuestionsUserForm::validateForm($form, $form_state);
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function security_questions_user_insert(\Drupal\user\UserInterface $account) {
  // During registration, save the user's answers.
  print_r($account->questions);
  die;
  if (!empty($account->questions)) {
    security_questions_user_answers_save($account, $account->questions);
  }
}


texts:
I've created a content type for authenticated users to use, to create and edit & delete their own of. I have set up the permissions and can get access as a authenticated user to the forms directly via node/add/story & node/19401/edit.

Now i want to use the form on another page, to be used in a block within a panel.

$form = drupal_get_form('story_node_form');
return drupal_render($form);

using drupal_get_form doesn't seem to work correctly is there another function I should be using to pull in the form?

*UPDATE

I managed to get it to work using node_add

include_once(drupal_get_path('module','node') . '/node.pages.inc' );
return drupal_render(node_add('story'));

is there any security issues with this method?


texts: How can I check I run the Drupal Commons profile?

texts:
Yesterday I installed Drupal Commons on http://campus-24.com/. The version was grabbed from http://commons.acquia.com/home, but I am not very sure I have chosen the Drupal Commons installation profile.
In general the installation ends up with the appearance of exactly the same theme that is shown on http://commons.acquia.com/home.
It is pretty interesting that the above mentioned site does not feel/look, and it does not behave as a Commons. In short: The look and feel, and the behavior of the site is totally neurotic! If I look in the administrative area, I have only the following 6 themes in the system to choose between:

Bluemarine
Chameleon
Marvin
Garland
Minnelli
Pushbutton

So I guess there isn't a clear evidence that I have installed the wrong profile, the Drupal standalone installation profile, and not the Commons profile. Where can I have a closer look at which profile is active?
Update
I finally got it: After several trials, I ported over an installation of the Drupal Commons that was smoothly installed on the local Lampp.


texts: Options aren't working in my views UI.  JavaScript is enabled.  Example, if in views, if I want to re-write output, and I click the checkbox, I don't get more options.


texts:
How can I add a section to the admin/config route and populate it with my own modules? In Drupal 7 it was easy, but I can't figure it out now in Drupal 8. The closest I can get is adding my modules to the Configuration Menu List that appears in the sidebar.

module.links.menu.yml

module.admin_settings:
  title: 'Module Admin Title'
  description: 'Module Admin Desc.'
  route_name: my_module.my_module_settings
  parent: system.admin_config