texts: Programmatic menu link for a view with contextual filter and no parameters in the path

texts:
Related question (my question is when contextual filters are NOT in the path): Generate menu links for a view with contextual filter and parameters in the path

In mymodule.links.menu.yml I have defined a link:
MYMODULE.fruits-apple:
  title: 'Apple'
  route_name: view.fruit_list.page_apple
  parent: MYMODULE.fruits
  weight: 5
  menu_name: fruits-navigation

The view page view.fruit_list.page_apple has the path /fruits/apple.
When on a page other than /fruits/apple, the link appears in my menu and allows access to the view. When on the parent page (/fruits), it appears expanded under the parent link in the menu.  But, on /fruits/apple, the link is not shown.
I checked the route with /devel/routes and found this:
Route name: view.fruit_list.page_apple
Path: /fruits/apple/{arg_0}
I think the problem is that I am not setting {arg_0} in mymodule.links.menu.yml.  I think this is the problem because I have links to views with routes that do not have {arg_0} in them and they display properly.
{arg_0} is a contextual filter for the User ID:
When the value is NOT in the URL: Provide default value (User ID from logged in user)
I am using the view path as /fruits/apple, so I never explicitly set the user ID for the contextual filter; instead, I rely on Views to automatically pull in the value.
In this case, how can I set the route parameter {arg_0} for my view so that the menu link appears properly on the view path?
I tried adding route_parameters: { arg_0: '' } and route_parameters: { arg_0: 'NULL' }, but that didn't help.
MORE DEBUGGING
When I create a link in the menu UI to the path /fruits/apple and then go the page /fruits/apple, I see BOTH my menu UI link and my module-defined link.  But if I disable or delete my menu UI link, then my module-defined link is not shown.
In the same way, I can create a menu link using the options in the Views UI, which also causes both my Views UI menu link + module-defined menu link to be displayed on /fruits/apple.  When I remove the Views UI link, the module-defined link is also no longer displayed.
If I delete the contextual filter on my view, then the module-defined link is also shown.


texts: Is it possible to create/manage Roles using a .yaml file?

texts:
I'm trying to secure some REST URLs that are present in my ApiController.php so that users with certain privileges can access these REST APIs.
I created some users and assigned them with some Roles using the below link:

https://www.drupal.org/docs/user_guide/en/user-concept.html

As you can see, I'm creating roles in Drupal Admin following below steps:

Drupal UI → People → Role → Add New Role     // line 4

After that, I added a few permissions in permission.yml:

xyz.permissions.yml

edit permission:
  title: 'edit permission'

And updated routing file to secure APIs:

xyz.routing.yml

xyz.update:
  path: '/update'
    _controller: 'ApiController::update'
    _permission: 'edit permission'

This is working fine. i.e. users that have "edit permission" can access URL "/update".
But, I don't want to do step on line 4 rather I would like to use some .yaml file to create Roles.


texts: How do I check if an image field is empty in a template file?

texts:
I am trying to check if the user_picture field is empty using the twig template, but I am not able to do this.

I tried lots of ways:-

{% if node.user_picture.value %}
{% if node.user_picture.entity %}
{% if content.user_picture.value %}
{% if content.user_picture|render.entity %}
{% if content.user_picture|render %}

Sample of code:

  {% if node.user_picture.value %}

User-picture 02

    {{ user_picture }}
  {% else %}

Anymonus-picture 02

  {% endif %}


texts: How to match a Drupal path in Apache config

texts:
My D8 site uses the usual convention in .htaccess to rewrite non-file requests to index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*) index.php [L]

However, if I try to perform a location match in my Apache 2.4 httpd.conf virtualhost, it fails because it seems that REQUEST_URI is set to index.php.

<Location /foo/bar>
  #Directives that should fire when accessing /foo/bar but don't
</Location>

<Location /index.php>
  #Directives that do fire when accessing /foo/bar
</Location>

Any ideas for getting this to work?  I have tried:

<If "%{REQUEST_URI} =~ m#^/foo/bar#">
  #Directives that should fire when accessing /foo/bar but don't
</If>

<If "%{REQUEST_URI} =~ m#^/index\.php#">
  #Directives that do fire when accessing /foo/bar
</If>


texts: How to programmatically add a user to a group in Drupal 7

texts:
I am trying to programmatically create a group node and add a user to that group in Drupal 7. The group node is being created just fine but the user is not being added to the group and I am not getting any errors. I am guessing I am using the og_group function incorrectly but I am not sure. What am I doing wrong?

function MYMODULE_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1;
    $node->promote      = 0;
    $node->comment      = 1;

    $node->og_description   = t("OG Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    $account = user_load(2);

    og_group($node->nid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => "OG_MEMBERSHIP_TYPE_DEFAULT",
            ));

    drupal_set_message(t("Finished"));
}


texts: How to vary classes depending on content type?

texts:
In my page.html.twig template file, I'm looking to set classes depending on the content type the page is being viewed. I pretty much have two options, if the page being viewed is a program page, then I want one style applied to the div, if it's anything else, then the other style can be applied.

{%
  set aside_classes = [
    node.content-type is 'program' ? 'program',
    node.content-type is anything else ? 'standard'
  ]
%}

I know the above code is not proper but it's an example of what I'm trying to achieve.

I would then have the following code below on my div:

<div{{ content_attributes.addClass(aside_classes) }}>

Am I going about this right or is there a better way to achieve this?

EDIT:
Here are my kint variables. Not sure if this helps at all?:


texts: All instances of block are not getting removed

texts: This question is a continuation of this Block in Drupal 8, The second problem I am facing is that suppose I select block made for comment section and place it under Sidebar second section and afterwards deselect comment from configuration setting then after clearing cache the label for comment from block section is removed but block placed under Sidebar section still remains with default message for broken blocks "This block is broken or missing. You may be missing content or you might need to enable the original module.".What changes should I make so that this message is removed ? Thanks.


texts: How can I inspect $element variable in theme function?

texts:
I would like to change formatter of Field Collection Table, so that class added to a table row corresponds to a value of field of field collection item. As a first step, I would like to inspect theme function of that module. However, if I modify it to:

function theme_field_collection_table_multiple_value_field($variables) {
  $element = $variables['element'];
  $header = array();
  $cells = array();

  // Order field widgets by their widget weight.
  $instances = field_info_instances($element['#entity_type'], $element['#bundle']);
  uasort($instances, '_field_collection_table_sort_items_widget_helper');
  foreach ($instances as $field_name => $instance) {
    if (empty($element[$field_name])) {
      continue;
    }

    $header[] = _field_collection_table_get_title($element[$field_name]);
    $cells[] = array('data' => $element[$field_name]);

    // Remove the original field to prevent duplicate printing.
    unset($element[$field_name]);
  }

  $element['field_collection_table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => array($cells),
    '#weight' => 0,
  );

  $element['#sorted'] = FALSE;
  dpm($element);
  return drupal_render_children($element);
}

no krumo element is displayed. I cleared both opcache and drupal cache several times, but the problem persists. Also, I did deliberate error to make sure, that theme function applies. Do you know, what am I doing wrong?


texts: What is $delta for in Field API hook_field_widget_form?

texts:
d.o defines it as such:

  $delta The order of this item in the array of subelements (0, 1, 2, etc).

So that you can use it as an index into the $items array, but i can't seem to wrap my head around when the $items array would have more than one element.


texts: Limit number of event registrations per month

texts:
I'm creating a membership-based site in D7, using Date, Calendar, and Entity Registration (which was very easy to setup). Only authenticated users may register for an event.

I'm trying to limit the number of events an authenticated user may register for during a certain time period (probably by month or by quarter), and I'm stuck. I created a field called 'Registration Count' for user accounts. And I created a rule that increments the counter when the user registers for an event.

But I'm trying to figure out:

How do I prevent a registration based on the user's current registration count? I got as far as creating a rule that is triggered prior to a registration and checked his current registration count. And I can display a warning, but the registration still goes through. Isn't there an action I can assign that would halt the registration?
How can I reset the registration counter field for all user accounts back to zero at a certain interval? I can't find access to user fields on that broad level.

Adding more details:

I have a node type called "Event". My registrations are entities. This is out-of-the-box functionality for the Entity Registration module, and it was very simple to get it up and running.

Each user has a field called field-registration-count. When a user registers for an event, I have a rule set up as follows:

Event: After saving a new registration
Action: Set value site:current-user:field-registration-count, add offset 1. This increments the user's registration count by 1.

I have another rule:

Event: Before saving a registration
Condition: site:current-user:field-registration-count > 2
Actions: Page redirect, and then Show a Message on Site

On the third registration, the page redirect happens as expected, and the message is displayed, but the registration is still saved. Based on the provided event named "Before Registration", I think I'm tapping in a the right time; I just can't find an action to cancel the registration itself

Note: When a user actually registers, it doesn't create a node. The Entity Registration module creates an entity type instead, and each registration is an entity.


texts: Upgrading and creating entity references

texts:
I have a Drupal 6 site which I plan to upgrade to Drupal 7, but I would like to do some alterations to one of the content types on the upgrade.

When I built the site I did not use D6 Node References on a content type when I probably should have; for example, instead of referencing a company content type containing fields for its name and website, I just have two plain fields, company name and URL.  I would like to find a way to fix this on the 'new' site.

Do I try to fix this on the Drupal 6 site then do the Drupal 7 upgrade, do the upgrade and then create the D7 entity references, or can I, as part of the upgrade, build the entity references automatically?

I'm not planning on doing a Drupal 7 or Drupal 8 data migration, so that option is out.


texts: CSS defined in library is not included, but theme works

texts:
themes/custom/teleci/teleci.info.yml:

base theme: bartik
core: 8.x
name: Teleci
package: Custom
type: theme
version: "1.1"
libraries:
  - teleci/global-styling

themes/custom/teleci/teleci.libraries.yml:

global-styling:
  version: "1.1"
  css:
    theme:
      css/override.css: {}
      css/style.css: {}

I also have custom template in themes\custom\teleci\templates\block--teleci-branding.html.twig that is loading correctly - that means the theme works. But the CSS files are not included (they are not in the generated HTML).

I tried

php drupal.phar cr all
setting bartik as default and then set my theme back
clear browser cache
open in private window
disable JS/CSS minification in settings
check both yml files in yamllint.com
disable base theme (bartik)

I'm out of ideas and would appreciate any help :(

Update: I created minimal theme (that does not work as well) for you to test. Could you please test it and let me know if it works for you? https://github.com/tomasfejfar/drupal-simple-theme/ (i have it in /themes/custom)

Update 2: the mini-theme works when I fixed a small bug that is not present in my theme. So there is something about my theme that makes it break.


texts: How to set up a cron job that runs for a specific rule?

texts:
I have a 2 rules that should run each on a specific time interval instead of the regular cron job setting.
I have a list of "Sessions" (entity type) that should be evaluated to see if their booking has expired, if their starting date is in the past, etc. and then certain settings should be updated  on each.
I have another list of "Events" (entity type) that does something similar but shouldn't be executed with the same frequency as the Sessions.
Both are rules components.
My first problem
These components fire when I force run my cron job with Elysia Cron module and that works. But it should be automatic. So I have assigned the "rules_cron" job to a new channel, "channel 2" and it should run every hour but it doesn't do that. rules_cron apparently runs every 48 hours or so.

My second problem
What I really need is the Session component to run every hour and the Event component to run every 15 minutes?
What am I doing incorrectly and how do I accomplish that?


texts:
After upgrading to Drupal 7, all the pictures of the items have disappeared.
In the View UI editor, I cannot add an image content and it says "Content manager: broken/missing".

Help?


texts: Commerce Product Display Node using Multiple Fields?

texts:
Hello after reading How do I display my products? I was impressed how easy it is to have a display node have a simple attribute system for a product.

For example Clothes can have a product reference field for different sizes.

For more complex use case can we have multiple fields?

For example Clothes size and color with each combination having a different product. I understand this requires many more products as a result.

Has anyone talked about this use case or know of a workflow / module here?


texts: More information than standard "Site Details", also to be available as tokens

texts:
Is there a way to add additional fields to the config/system/site-information area such as business owner, "business location", "hours of operation", "phone number", etc. I would then like to be able to use that information throughout nodes and blocks as tokens.

That way if the details change, they will change throughout the site. This is particularly handy when using token filter for document templates on uses for multiple sites, like privacy statements.

Is this possible, or is there another way to add this functionality?


texts: How can I remove the checkbox from tableselect form header only?

texts:
How can I remove the checkbox from tableselect form header (Drupal 7) only? I am looking for any configuration if available that can be applied in the below sample code:

$form['listings'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No Listing available.'),
);


texts:
Why doesn't this cache anything?

$cache = [
 '#cache' => [
   'tags' => [
     'test'
   ],
   'max-age' => -1
 ]
];
$response = new CacheableJsonResponse($data, 200);
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($cache));


texts: How to apply Strikethrough text for broken link(s) in Drupal 7

texts:
Lets say I've created an article page. which consists several paragraphs (like in Wikipedia). The paragraphs may contains links to external pages.

I would like to validate the external links while page loading. Meaning if the external links are not available/ doesn't exist I need to make the link text strike off.

Let's say in the following example link for  'Website' is not available. So I need to show that link as follows

  Checkout this Website

I've verified Link checker module for this. Using this we can identify broken links  under Reports -> Broken links. (when cron runs)

Is this module helpful to achieve my requirement? Any suggestions?


texts: How to show Image Alt Value with View Slideshow Module?

texts: I am working on the Image Slide show using  View Slide show  module in drupal 8.Its working fine for Image Slide show but I want to know How can I show the Image Alt value below the Image and its change with the slideshow.


texts: 8 - Register form automatically fills in input fields

texts:
I am using the core user-register-form to let users register to my site. When I first want to register a new account the form is displayed as followed:

Now, when I enter credentials and submit the form, the user is created. I can login and out with the created user.

However, if I want to register ANOTHER new account the form automatically fills in the e-mail and username of the user I just created.

I have tried several things that did not solve the problem:

Clear Drupal cache
Close browser and re-open
Kill browser and re-open
Open incognito browser
Clear browser cache
Disabled browser auto-fill

I also tried clearing the inputs using jQuery val(''); but then the form doesn't submit properly.

I assume this has something to do with drupal core? Please advice!


texts: listing all the pages of a custom content type

texts:
I would like to know the appropriate way to listing the contents in a single page of type "news". Let me clear it once again, I have a "news" type custom content type.

Now i want to list all the pages of type "news" in a separate(say about us) page and styling them. Prior to this I have created a template file in my custom theme's template directory named as "node-news.tpl.php". Thanks In Advance.


texts: Field twig template : override HTML output

texts:
Still converting my D6 theme to D8 and I need to override the HTML output for a custom field in a node twig template.
After some readings, I don't find an example for this.
My field contain files and I want them to display in a HTML list instead of a div + span.
So I created a file named field--field-fichier-joint.html.twig and added inside the code from this post , but I get a WSOD.
This is my actually code:

{% extends "@stable/field/field.html.twig" %}

{# Create classes array #}
{% set classes = [] %}

{# BEM inspired class syntax: https://en.bem.info/
   Enable this code if you would like field classes like "article__tags", where article is the content type and field_tags is the field name.
{% set classes = classes|merge([
  bundle ~ '__' ~ field_name|replace({'field_' : ''})|clean_class
]) %}
#}

{% set attributes = attributes.addClass(classes) %}

{#
  Ensures that the visually hidden option for field labels works correctly.
  @todo: Remove when https://www.drupal.org/node/2779919 is resolved.
#}
{% set title_attributes = title_attributes.addClass(label_display == 'visually_hidden' ? 'visually-hidden') %}

  {% for item in items %}

{{ item.content }}

  {% endfor %}

If someone can help me.
Thanks

EDIT: 4k4 solution work fine but I need to add some classes and I saw a very smart solution but I need help to use it. This is here

EDIT2: adding classes work but how can specify which one to apply to an element ?
Then when I want to add some flexibility to the code with this:

{# Définition des variables et classes #}
{%
  set classes = classes ?: [
    'field',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class
  ]
%}
{% set wrapper_element = wrapper_element ?: 'ul' %}

{% set element = element ?: 'li' %}

{# Mise en forme sortie HTML #}
<{{ wrapper_element }}{{ attributes.addClass(classes) }}>
  {% for item in items %}
      <{{ element }}>{{ item.content }}</{{ element }}>
  {% endfor %}
</{{ wrapper_element }}>

I get Multiple items like this, why ?:

< Un fichier joint pour test Autre fichier test > Un fichier joint pour test Un fichier joint pour test Autre fichier test > < Un fichier joint pour test Autre fichier test > Autre fichier test Un fichier joint pour test Autre fichier test >

2- Adding classes
I want to add classes to my HTML output, in particular, the odd/even and I found this code but only odd class is applied:

{%
  set li_classes =  classes ?: [
    'field__li',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class,
    'ligne__' ~ cycle(['odd', 'even'], loop.index0),
  ]
%}

then, my li classes inherit from ul classes, how can I avoid this ?
This code work better but the cycle loop result is out of the class..

{{ item.content }}

render:

EDIT: the Final code

{# Les classes a jouter à la liste UL #}
{%
  set ul_classes = classes ?: [
    'field__ul',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class
  ]
%}

{# Mise en forme HTML #}

  {% for item in items %}
      {# Les classes a jouter aux lignes LI #}
{%
  set li_classes =  classes ?: [
    'field__li',
    'field--' ~ field_name|replace({'field_' : ''})|clean_class,
    'ligne__' ~ cycle(['odd', 'even'], loop.index0),
    ]
%}

{{ item.content }}

  {% endfor %}


texts: Can you dynamically request a (cached &) scaled image via imagecache in css?

texts:
Is there a way to request a scaled image via imagecache by adding width/height parameters or a preset-reference to the image url within css? For example:

Obviously, to scale down an image in css, you can do the following:

HTML:

<figure id="logo"></figure>

CSS:

#logo {
  background: url('path/to/image.jpg') no-repeat;
  width: 50%;
  height: 50%
}

This will still load the full sized image and scale it down on the client side. I am wondering if something like the following is possible within CSS, so you dynamically request a scaled image via imagecache:

#logo {
  background: url('path/to/image.jpg?width=50px&height=50px') no-repeat;
}

or

#logo {
  background: url('path/to/image.jpg?preset=existingimgpreset') no-repeat;
}

Which will scale down the image on the server side and hopefully will return a cached version of it when possible.


texts: Adding temporary field to form to print ID's

texts:
When writing modules, especially in the "hook_form
_alter" hook, I find myself in the same situation many times:

I want to control some $form fields and I'm searching the field ID, the right attribute convention, etc.

I'm trying to print all the fields and their attributes to the output page so I could do that every time I need information about a form fields.

How can I print all the fields complete attributes?
I need to stick it temporarily in the page - how can I send the details to the page (I don't know what are the fields ID's...)?


texts: Get the user location during registeration process

texts:
I am developing a drupal site along with the mobile application.
I want to store the latitude , longitude of the user who registers in my site...
I can see there are many location based modules available but i want to use the one which affers the map ui on the registeration form and the user types
in its address and through reverse geocoding i could fetch the latitude and longitude of that place.

Basically i need location module during registeration form
Thanks


texts: Unable to load URL when drupal is installed on a server

texts:
My drupal URL was loading normally until when I deleted two modules in the Windows server.Now after deleting the modules from the server the site is not loading.
I know that deleting a module does not result in the URL not loading it simply removes the module from the Module List.

I can't exactly find out what exactly is the reason behind this

[Update]I have checked under my Modules Menu and verified that both the modules are disabled and then un-installed from the modules list.


texts:
I'm using the config_split module to split configuration to an installation profile, that I use in multiple Drupal sites.

I have 2 sites using the same installation profile, both using the same config split settings.

Here's a list of configuration that I have split to the profile.

The content type (article)
Taxonomy vocabularies
Media types
Media library views and settings

I have 4 content types on one of the sites, but I only want to split the article content type.

The problem is that some fields from the other content types are automatically split because they depend on either media or taxonomy.

This is the node configuration that I'm splitting:

  core.base_field_override.node.article.*
  core.entity_form_display.node.article.*
  core.entity_view_display.node.article.*
  core.entity_view_mode.node.article.*
  field.field.node.article.*
  field.storage.node.article*

All fields from the article content type are all named article_FIELD_NAME.

How can I avoid that config split also splits depending configuration?


texts: Will importing a View that already exists merge with what isn't there in Drupal 7?

texts: I have a dev and prod instance of my site. I cloned my Prod to my Dev server. Now I created a new display block inside an existing view on Dev. I tested it and it works. Now i want to export it to my Prod, but it has the same View name. I can manually create it on prod, but thats the slow way of doing it. If i export the view code and paste it to my prod, would it throw an error saying that view exist? Or would it just merge the changes and add in the new display i created?


texts: MarkupInterface interoperability with other PHP frameworks

texts:
Situation in Drupal 8

Drupal 8 introduces a few classes and interfaces for safe markup:

Drupal\Component\Render\MarkupInterface
Drupal\Component\Render\FormattableMarkup
Drupal\Core\StringTranslation\TranslatableMarkup

The purpose is

to mark a string as being safe for use in html, without further sanitization.
to have the string be lazy-evaluated.

The problem seems to be that all of these are specific to Drupal.

Use case

I am designing an API I want to publish as a composer package, that should be used and implemented within Drupal 8 but also work outside of it. It should not depend on anything within Drupal.

There are interfaces that can return string labels, or arrays of such labels (e.g. to act as option labels in a select element).

Implementations within Drupal will want to use the t() function, which returns TranslatableMarkup objects. But the interface or the calling code know nothing about Drupal's TranslatableMarkup or MarkupInterface.

Solutions considered so far

One option would be to require all implementations to return plain strings, which they can do via (string) cast, or by calling the __toString() method. This would work but it feels unnatural.

Another option would be to introduce a custom TranslatableString object which my own API can understand. This would replace a Drupalism with a my-own-ism, and also feel clumsy for implementations within D8.

Another option would be to allow the interface to return arbitrary values and later attempt to convert them to strings using either a flexible adapter layer, or attempting to call the __toString() function. This would make it harder to require a specific return type, and detect if an implementation returns "illegal" values.

Question

Have there been any attempts to make a "bridge" between Drupal's MarkupInterface (EDIT: And TranslatableMarkup) and the larger PHP ecosystem?

Ongoing discussion

There are some comments below which point to interesting directions.

I'd say the main question is still open: How can we bridge the Drupal-specific classes and interfaces to the outside world? Are there Drupal-agnostic versions of these classes and interfaces?


texts: I want to send the username of the person submitting the form along with form data

texts:
I wanted to know how to get the username for whoever submits a form so I can pass it to db_insert along with form data.

Sorry, I'm new to Drupal and php. I'm just try to learn.

Yes, it is custom code. Here is the form. I have based it on tutorials I've found so far.

function input_simple_form($form, &$form_submit) {

$form['color'] = array(
    '#title' => t('color:'),
    '#type' => 'textfield',
    '#required' => TRUE,
            '#description' => t('What is your favorite color?'),
    '#prefix' => '
',
    '#suffix' => '

',
    );
$form['TV_Show'] = array(
    '#title' => t('TV_Show:'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#description' => t('What is favorite TV show?'),
    '#prefix' => '
',
    '#suffix' => '

',
    );

$form['input'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#submit' => array('input_simple_form_submit'),
    );

return $form;
}

Then I send the data to database:

function input_simple_form_submit($form, &$form_state) {

// Display a message upon successful submission.
drupal_set_message(t("Added @color @TV_Show", array('@color' => $form_state['values']['color'], '@Name' => $form_state['values']['TV_Show'])));
$id = db_insert("TestForm")
->fields(array(
    'color' => $form_state['values']['color'],
    'TV_Show' => $form_state['values']['TV_Show'],
    'SubmitBy' => $user->name,
    ))
->execute();
}

I'm not sure how to pass $user to the submit function. Hope that helps.


texts: How to set DB log only to log CRON TYPE and SEVERITY NOTICE message?

texts:
I want to log only CRON TYPE and SEVERITY NOTICE message in db log , want to exclude all other types like notice, alert, critical, info, debug etc.,
Is there any way to prevent this, or should i write any custom coding for this?
if custom coding for where i can prevent logging other types in DBLOG.


texts: Restrict menu item to certain roles in TB Mega Menu

texts: I am currently using TB Mega Menu on D7 to configure my main menu. One of the main menu item is accessible to both anon & authenticated users.I would like to have a block attached to this item as a drop down but it should be accessible only by certain roles - not all authenticated users. I have enabled block visibility restrictions for this block by the user roles I want. But I am still able to view this block as part of the menu as an anon user. How do I restrict this?


texts:
Its quite annoying to have to type -v.

Is there a way to change the drush settings so that it will always use verbose mode so I dont have to bother typing -v?


texts: Considering two solutions for adding classes to a menu

texts:
Ive subthemed the main bootstrap theme, and i just want to add classes to my main menu and menu items, so my two solutions would be to:

1.copy menu--main.html.twig  into my templates folder, that way overrideing the original, and then just delete all of that attributes/class logic they've added and add my own classes.

This was my initial idea, but then i looked at their attributes logic:

{#
/**
 * @file
 * Default theme implementation to display a menu.
 *
 * Available variables:
 * - menu_name: The machine name of the menu.
 * - items: A nested list of menu items. Each menu item contains:
 *   - attributes: HTML attributes for the menu item.
 *   - below: The menu item child items.
 *   - title: The menu link title.
 *   - url: The menu link url, instance of \Drupal\Core\Url
 *   - localized_options: Menu link localized options.
 *
 * @ingroup templates
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
      {% if menu_level == 0 and item.is_expanded %}

        {{ item.title }}
      {% else %}

        {{ link(item.title, item.url) }}
      {% endif %}
      {% if item.bel{#
        {{ menus.menu_links(item.below, attributes.removeClass('nav', 'navbar-nav'), menu_level + 1) }}
      {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

I Thouth that there had to be a good reason why they have it, so i was thinking about doing the second solution:

preprocess function for the template and add the attributes there. But the logic would be something like:

    function itkweb_preprocess_menu(&$variables) {
         if($variables['menu_name'] = "main") {
             $variables['attributes']['class'][] = 'someclass';
           }
     }

So basically the question is why would i keep the attribute logic, or why would i just delete it?

Another question is, what is the name of the preprocess function, if i wanted to target the menu--main.html.twig specifically? the menu would be
_preprocess_menu    so ive tried to mix in main, but i can't get it to work.

Thanks!


texts: How to expose variable from php to js - and keep it updated?

texts:
drupal_add_js works to pass variables from php to javascript, and there are plenty of examples. But I want the variable to update without a new page request.

I have a page request that kicks off some long-running code in the background (using background_batch and the Batch API), during which a variable is updated occasionally. When it changes, calling drupal_add_js again doesn't do anything. Then I tried to implement this but it doesn't seem to work either. I've use ajax with the Form API, but that is a specific request that returns to an element just once - this is going the other way (php to js ad-hoc).

Summarizing: How to push a php variable to be available in javascript at any point it time, from any Drupal code?


texts: Multiple aliases per node (and active trail)

texts:
Our site is split down the middle for tenants and landlords. But we have content the is the same for both such as "how to report antisocial behaviour".

User would normally navigate something like "Home > Tenant > ASB" or "Home > Landlord > ASB".

Duplicating content obviously isn't good, but we aren't worried about SEO, we are worried about maintainablity and context for the user.

So, I looking for a way to provide 2 aliases for a piece of content, and have the active trail show accordingly.

I found this, which suggest that symfony should be able to handle it, but I can't find how I would make it work in Drupal.

I can add a second alias, but I always get forwarded to the last one entered.


texts: Drupal commerce - passing attributes from one module to other

texts:
Firstly I am new to Drupal commerce and start learning it on the job as required. So if you see my question as basic functionality in Drupal commerce, please pardon me.

Question: I have a simple commerce site and it look like as follows: Product view -- Shopping cart -- checkout

After checkout, I am adding a new custom module(creating an account for the user and few other things). I need to get the attributes of the product from the shopping cart module. How can I retrieve that information from the shopping cart module to the new custom module that I am building.

Thanks in advance.


texts:
For my use case, I don't need this Revision information section to appear on my page. (I am using revision, so it has to be enabled on the content type).

What options are there to 1) disable this seciton , or to 2) hide it?


texts:
how can I access to my user role thanks to my user custom field ?

I have an user field called "custField" and it's value (example : 123456). I need to check all users that have "123456" as value.

Then, I need to check if this user as the role "director".

But I don't know how to access role thanks to another field.

EDIT :

See this loop :

foreach($retraitDoublons as $valUnique){
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['field_custVal' => $valUnique]);
  $user = reset($users);
  $user_has_role = $user && $user->hasRole('directeur_cr_');

  dump($user);
  dump($user_has_role);

  echo $valUnique . "<hr>";
}


texts: How to override core taxonomy/term/% with a view?

texts:
I have enabled the taxonomy/term/% view provided by the Views module but taxonomy term views are still handled by the core. Modifications has no effects and hooks such as  hook_views_pre_render() are not invoked.

However, views explicitly specifying a term such as taxonomy/term/5 work.

Do you have any idea on how I can override the core default taxonomy?


texts:
Following this post:
    http://www.sitepoint.com/creating-a-new-drupal-node-type/

I have tried to create a custom content-type from code like here:

Update code
https://github.com/jmvelasco/drupal

But the way, after install/activate it I get these warnings:

Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 270 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in isset or empty in FieldInfo->getField() (line 274 of /users/gen00/web/html/modules/field/field.info.class.inc).
Warning: Illegal offset type in FieldInfo->getField() (line 291 of /users/gen00/web/html/modules/field/field.info.class.inc).

Although the content-type is apparently created.

EDIT the content could be created once I update the base value

But when go to Create Content of this new content-type, I have the following error

array
  'error' =>
    array
      0 => string 'Warning: Missing argument 3 for node_form(), called in /users/gen00/web/html/modules/node/node.pages.inc on line 161 and defined in node_form() (line 107 of /users/gen00/web/html/modules/node/node.pages.inc).' (length=324)

Also, when uninstall the module I get this notice:

Notice: Trying to get property of non-object in content_access_node_type_delete() (line 524 of /users/gen00/web/html/sites/all/modules/contrib/content_access/content_access.module).

I can't figure out where is my mistake and I have come here wondering if any drupal-ninja could help me to understand my mistake and create this content-type correctly. Anyone?

Thanks in advance.


texts: Displaying multiple child-grandchild-relationships properly through Views

texts:
I am using the most recent versions of Drupal (7.14), Views (3.3) and the Entity reference module (1.0 rc3).

I have three content types. The first of them (parent) contains a node reference field to the second (child), which has a node reference to the third (grandchild). Each of these reference fields have unlimited values.

I have set up a block view, with relationships for both node reference fields, and have defined a contextual filter for the parent node id.

This is what I want to display in the parent node, each with summaries and a few other fields from the referenced nodes:

Child 1
Grandchild 1
Grandchild 2
Grandchild 3

Child 2
Grandchild 4
Grandchild 5

With displaying an unformatted list of fields, I get the following result (aggregation doesn't help at all):

Child 1
Grandchild 1

Child 1
Grandchild 2

Child 1
Grandchild 3

Child 2
Grandchild 4

Child 2
Grandchild 5

Any suggestions for how I can get the display that I want?


texts: Modify user profile page, not login page

texts:
I'm trying to edit the user profile page, not the login page.

However, with Drupal 7, the template for the profile and the login page is the same.

I tried to modify page--user.tpl.php, but it also modifies the login page. And modify user--profile.tpl allow to modify the order of the fields but not the entire page.

Do you know how to do it ?


texts:
I'm trying to ajaxify part of node form. I have a hook_form_alter that adds extra ajax property to a widget of select field. The problem I'm facing is the callback method / function, which is not fired when change is happening.

So this is my form_alter code which resides in accountancy_invoice/accountancy_invoice.module:

function accountancy_invoice_form_node_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_invoice_form') {

    $form['accommodation'] = array(
      '#type' => 'container',
      '#prefix' => '
Dave
',
      '#attributes' => array(
        'class' => 'user-full-name',
      ),
    );

    $form['field_invoice_customer']['widget']['#ajax'] = array(
      'callback' => 'Drupal\accountancy_invoice\Form\AjaxifyForm::customerValues',
      'progress' => array(
        'type' => 'throbber',
        'message' => NULL,
      )
    );

  }
}

This is my AjaxifyForm class which resides in accountancy_invoice/src/Form/AjaxifyForm.php:

namespace Drupal\accountancy_invoice\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\OpenModalDialogCommand;

class AjaxifyForm {
  public static function customerValues(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#user-full-name', 'Bryan'));
    $title = "Example Dialog";
    $content = "foo bar content";
    $options = array();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));
    return $response;
  }
}

It doesn't really matter at the moment what this ajax should do. For testing purposes I just want to change name from Dave to Bryan in #user-full-name and display sample dialog box.

In the console, each time ajax is triggered I got an error:

This is complete error message (it's trimmed in the screenshot):
↵An AJAX HTTP error occurred.↵HTTP Result Code: 200↵Debugging information follows.↵Path: /node/add/invoice?ajax_form=1↵StatusText: OK↵ResponseText: TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given, called in /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 441 in Drupal\Core\Form\FormState->setError() (line 1093 of /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Form/FormState.php).


texts: How to manage translations when a site is being re-installed frequently?

texts:
Sites built on a profile, will, during it's early development experience frequent re-installs.

If a translator makes changes to a site, these will get lost when the database is dropped.

What options are there for handling this, in a way that survives re-installs?


texts:
I've created a View in Drupal 6 which I am using to display a list of events. I would like to be able to filter the view by year via the path like this:

http://www.mysite.com/events -> gives me all events
http://www.mysite.com/events/2011 -> gives me the events in 2011
http://www.mysite.com/events/2010 -> gives me the events in 2010

I see that you can specify arguments in the path, but I can't seem to be able to access that argument to use within the filter controls for the view. Any help would be greatly appreciated.


texts: submit handler not working in custom.module?

texts:
I have a submit handler for a form im tryin to submit into webform submissions. i have the handler like this:

function custom_webform_submit($form, &$form_state) {
module_load_include('inc', 'webform', 'includes/webform.submissions');
module_load_include('inc', 'webform', 'includes/webform.components');
global $user;

$node = $form['#node'];
$sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']  ['sid'] : NULL;

if (!$sid) {
  // Create a new submission object.
  $submission = (object) array(
    'nid' => $node->nid,
    'uid' => $form_state['values']['details']['uid'],
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => $is_draft,
    'data' => webform_submission_data($node, $form_state['values']['submitted']),
  );
}
else {
  // To maintain time and user information, load the existing submission.
  $submission = webform_get_submission($node->webform['nid'], $sid);
  $submission->is_draft = $is_draft;

  // Merge with new submission data. The + operator maintains numeric keys.
  // This maintains existing data with just-submitted data when a user resumes
  // a submission previously saved as a draft.
  $new_data = webform_submission_data($node, $form_state['values']['submitted']);
  $submission->data = $new_data + $submission->data;
}

// If there is no data to be saved (such as on a multipage form with no fields
// on the first page), process no further. Submissions with no data cannot
// be loaded from the database as efficiently, so we don't save them at all.
if (empty($submission->data)) {
  return;
}

// Save the submission to the database.
if (!$sid) {
  // No sid was found thus insert it in the dataabase.
  $form_state['values']['details']['sid'] = $sid = webform_submission_insert($node,  $submission);
  $form_state['values']['details']['is_new'] = TRUE;

 drupal_set_message(t('The form has been submitted.'));
}

The part that seems to throw an error for me is  the following one.

if (!$sid) {
  // Create a new submission object.
  $submission = (object) array(
    'nid' => $node->nid,
    'uid' => $form_state['values']['details']['uid'],
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => $is_draft,
    'data' => webform_submission_data($node, $form_state['values']['submitted']),
  );
}

When I comment out these lines, the form just returns empty values.

Why is it not able to create a submission object, and what is giving me errors?


texts: How to detect Panelizer use in template_preprocess_html()?

texts:
In Drupal 7, you could look for $node->panelizer or use page_manager_get_current_page() to check if the current page uses a panelizer layout. How do you do that in Drupal 8?

I'm trying to add a body class if the current page contains a specific pane.


texts:
Main Modules:

Node access user reference
Node access node reference
Flags
Rules

I'm trying to give access to a user that clicks on a Join Project flag link.

I have a User Reference Field attached to a node call Project.  I'm wanting to tell Rules to add that user to the Node Access User Reference field, AKA "Join the group"


texts: Form API placeholder attribute rendered as "- Select -"

texts:
In a custom Drupal 8 module, I have a couple of Form API fields of '#type' => 'select':
<?
    $form['form-right']['field_role'] = [
      '#type' => 'select',
      '#title' => $this->t('Role'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Role Foo'),
        'bar' => $this->t('Role Bar'),
        'baz' => $this->t('Role Baz'),
        'quux' => $this->t('Role Quux'),
        'plugh' => $this->t('Role Plugh'),
        'xyzzy' => $this->t('Role Xyzzy'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Role'),
      ],
    ];

    $form['form-right']['field_contact_reason'] = [
      '#type' => 'select',
      '#title' => $this->t('Contact Reason'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#options' => [
        'foo' => $this->t('Contact Reason Foo'),
        'bar' => $this->t('Contact Reason Bar'),
        'baz' => $this->t('Contact Reason Baz'),
        'other' => $this->t('Other'),
      ],
      '#attributes' => [
        'placeholder' => $this->t('Contact Reason'),
      ],
    ];

Before a value is selected, the dropdown select picklists display the string '- Select -':

The client would like them to display the value in the placeholder attribute instead.
Have I done something wrong?


texts: Is it possible to display Entityform Types using Page Manager and Panels in D7?

texts:
Currently, I have a D7 site and my main Content region is displayed using Page Manager and Panels variants. I've created an Entityform Type that allows users to request an appointment, and I'd like this specific entityform type to have a different layout than what the default page.tpl.php provides.

I'd love to provide a default panels layout for all Entityform types, but I can't seem to find a way to do this (even using the Entityform Panels module.) I've come close by using the "Page manager existing pages", but submission pages display in the default page.tpl.php.

Is there a way to do this?


texts: How to detect if form is submitted, when form function is called twice

texts:
I have simple form in aside block:

function my_form($form, &$form_state) {
$form['save'] = array(
'#value' => t('Save'),
'#type' => 'submit'
);
return $form;

How can I detect (in this function), whether the form was submitted?
 I tried to add this line:

  $is_currently_submitted = !empty($form_state['input']);

But the problem, is that function my_form is called twice after submision, and in first call, the array $form_state['input'] is not empty, and in  second call it is empty. $_REQUEST array is empty in second call of function, too.
How can I then make changes in my form based on fact, whether the form was submitted or not?


texts: How do I iterate over values of a multivalued field with entity_metadata_wrapper?

texts:
For instance, I have a taxonomy_term_reference field with cardinality -1. If one or more terms are selected, I can use this code:

  foreach ($wrapper->field_myterms as $t) {
    $terms[] = $t->name->value();
  }

But if the field has zero values selected, this code throws:

EntityMetadataWrapperException: Unable to get the data property name as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 442 of sites/all/modules/entity/includes/entity.wrapper.inc).

This happens in a preview form step while creating a custom entity. The entity has not yet been saved but I am showing a preview of the properties and field data by creating a temporary entity with this code:

$entity = entity_get_controller('ams_survey')->create($form_state['values']);
$wrapper = entity_metadata_wrapper('ams_survey', $entity);


texts:
I have a view which creates a block of comments.  I have a comment.tpl.php in my theme folder which I use to theme the comments on the node.

To theme the view, I need a variant of comment.tpl.php and have tried the following:

comment-view.tpl.php
comment-views.tpl.php
comment-view--name-of-view.tpl.php
comment-view-name-of-view.tpl.php

After cache clearing each option the template is still not picked up.

How can I theme this view please?  By the way I am using the Omega theme.


texts:
I've NEVER been a fan of plugging a ftp address in a browser to access the files from a ftp server. I am trying to find a find a module  to allow drupal to host a FTP/File Manager. Example would be ANY host like Godaddy having a  File Manager in their CPanel.

I would rather use this module for FTP Access (allowing user to plug in username/password), which would allow them to reach a ftp server. Then give them the drag and drop functionality of Filezila, but all of this hosted on a Drupal site.

EDIT: Let me clarify that I am not looking for a ftp manager to upload drupal files. I am looking for a module that will act like Filezilla, in the fact that anonymous users can put in any FTP address, followed by username/password, then access the files on THAT FTP SERVER (from their Drupal site).


texts: What is the custom date format to display Days or Months ago in date field?

texts:
I want to display # Days Ago, or # Months Ago, or # Years Ago

Example: 3 Days Ago

I need to add custom symbols in the Date field in views.


texts: I am trying to print taxonomy ID of a node in the node body. In D7 there is no views filed to do that, so can someone help me with the PHP code?


texts: Renaming a webform handler - old class stuck in DB despite clearing cache

texts:
I'm creating a custom webform handler plugin based on the advice here, adding the class, in the correct directory, to an existing module.

I got the class name / some of the docblock info wrong initially - and need to change it.  Having run drush cr, the listing on  /admin/structure/webform/config/handlers seems to be stuck on the old entry.

I get "Cannot declare class ... because the name is already in use" errors when trying to add the handler to the form, for a class name that I'm no longer using, and which, having cleared the cache, definitely isn't in  cache_discovery.webform_handler_plugins in the DB.

I've also swapped browsers.

What am I missing?


texts:
I am having troubles exporting and importing a large numbers of CCK fields using Content copy (I need to have a file download/upload option).

Is there a SQL (or drush) command that can export and import CCK fields? I am interested in anything that bypasses the PHP memory limitations, 504 gateway time-outs, and what not.

Maybe I could still use HTTP from the webserver's CLI, something like wget  <export from content copy> >data.txt and wget --post-data data.txt <import via content copy>.


texts:
Ok so this is my first D7 project. Im stuck with the Search Block. First there is no way of customizing the search form block template to make the the search form input field and button inline to be displayed in one row. Ok i can live with that. But i cant live with not at all being able to overwrite the search result template. Neither does the preprocess_search_results() work nor do i find a way to overwrite the template for the search results. All i find is suggestions for D6 which all do not work.

Can please somebody tell me how to override theses templates and i am not talking about the form_ hooks like form_alter. I do not want to design forms by endless PHP Arrays. I want to template.

Thanks


texts: What values can I use for _entity_access in a configuration entity I am developing?

texts:
Looking at search.routing.yml, I noticed it contains the following code.

entity.search_page.enable:
  path: '/admin/config/search/pages/manage/{search_page}/enable'
  defaults:
    _controller: '\Drupal\search\Controller\SearchController::performOperation'
    op: 'enable'
  requirements:
    _entity_access: 'search_page.update'
    _csrf_token: 'TRUE'

entity.search_page.disable:
  path: '/admin/config/search/pages/manage/{search_page}/disable'
  defaults:
    _controller: '\Drupal\search\Controller\SearchController::performOperation'
    op: 'disable'
  requirements:
    _entity_access: 'search_page.disable'
    _csrf_token: 'TRUE'

While it's clear that the first part of the _entity_access value is the ID of the configuration entity used in the annotation for the class implementing it, I don't understand what I can use as part after the dot. Is it restricted to a set of values (e.g. add, update, use, delete), or is it a value the access controller class for that entity handle?


texts:
I need to get just the file name from a file submitted in a Webform.

In actions, I try to execute the following code at a "Show a message on the site" action:

$path = "[data:component-value]";/*a REPLACEMENT PATTERN that return http://mysite.com/files/webform/submittedfile.pdf*/
$file = basename($path);/*$file is set to "submittedfile.pdf"*/
echo $file; /*this *should* return submittedfile.pdf*/

But ALWAYS return http://mysite.com/files/webform/submittedfile.pdf

I've tested ltrim, rtrim, god_trim_for_me and chop. And it always return the full URL.

What am I doing wrong?


texts: I need to restrict certain search results from showing up for users and limit them to a specific content-type. This can be either the main search or some sort of custom search since it's the only type of post that will need to be searched on the site.


texts: Pre-populate webform default values with hook_form_alter

texts:
I have a webform (version 4.11 on Drupal 7) that is failing QA test because the javascript validation is not correctly attaching to an empty required form element-- the 'Please fill out this value' tag is going to the top of the screen instead of near the element that failed validation.

So as a work-around, I decided to add a hook_form_alter and a new validation callback, to manually perform the validation. I am setting the error messages with drupal_set_message.

It turns out that the $form and $form_state arrays for webforms are apparently different from the typical form. Instead of $form_state['values']['field_key'], I found them here: $form_state['input']['submitted']['field_key'].

However, I can not figure out where each field's #default_value key resides in the $form array. I would expect it to be $form['field_key'], but it's not there.

How can I pre-populate the default value of form elements in a webform with hook_form_alter?


texts: Modify Drupal error handler without killing kitten

texts:
Drupal 6's common.inc file includes:

  // Set the Drupal custom error handler.
  set_error_handler('_drupal_error_handler');

If I'm following the logic correctly, this results in all PHP errors going to Watchdog (if enabled).

I'd like to continue using Watchdog (not syslog or similar modules) for everything but PHP errors. PHP errors should go to a file (i.e., the error_log that is configured in php.ini).

I'd prefer not to patch Drupal to remove its use of set_error_handler(), so I'm looking for some ideas. Perhaps I can make my own call to set_error_handler() in a hook_init() or settings.php? Any ideas?


texts: How to place the page title and local tasks tab in a Panels region?

texts:
Is it possible to move the displayed page title (h1) and the local task tabs below it (the 'view' and 'edit' node tabs) to a region? Panels displays these by default for node/% page overrides.

I can add the local task tabs to a region of my choice, but I can't see how to remove the default node local task tabs.

And while I can set the page variant to 'no title', that's not really what I need, I want to define the region where it should be shown. I can add the 'Page title' from the page elements Panels content in the region I want, but it is empty when I set the page variant to 'no title'. I could add the title field and wrap it in h1 tags myself so I can use the 'no title' setting, or hide the first occurrence of the h1 with css and use the extra 'Page title' element, but it seems there should be a better way.


texts: Prompt to translate a content after creating a new content

texts: In my drupal site, I want to add a prompt informing editors that they must add a french version of an article (or any content type).  I tried doing this using Rules but there is no way to check if a content type has been translated to French.. CAn anyone shed some light? Thanks!


texts: Node ID is missing in contextual filters

texts:
The node ID is missing in the view contextual filters.

How can I use the node ID as contextual filter?


texts: How to add a text field to views exposed filter results?

texts:
I have a view that shows prices for different activities.

Each price is a content type called Activity. On the content type, they choose the activity from a select list, enter the price and save. The view then groups the price packages by their activity, and there is an exposed filter to show them with ajax.

I now want to add specific price and booking information to display in the footer of the view for each activity. This text needs to be able to be changed by my client.

What im struggling with is where I put the text fields for the client to fill in, and how i reference these in the view.

What ive tried...

I tried adding field collection items to the page they are displayed on, so my client can edit that page, and add a field collection item for each activity. Then i show those results in an embedded view inside the footer of the original view, telling it to inherit contextual filters, but that just shows all of the results.
I also tried adding a new content type using the same activity select list field, with a body field for them to add. But the same happens as above, the attaced view just shows all results, and pays no attention to the exposed filter from the main view.

Can anyone help?


texts: How do I pass a string from a PHP field to the PHP filter?

texts:
Is there any way to pass a string from php field to php filter?

on the PHP FIELD I can tell if a product has discount or not ( i think because the field formatter render the field_price in a way that triggers the discount rules) and if there is a discount I can set a variable on/off based on the output of this formatter.

This custom discount variable created with PHP FIELD I need to pass it to the PHP FILTER to control if a product must needs to be shown or not (sorry for my bad English)

PHP FIELD CODE

<?php

// $var1 will take value 0.00E or -94.99E (the last value is an example)
$var1 = strip_tags($data->field_commerce_price[0][rendered]);

// $var2 will take value 0 or -
$var2 = mb_substr($var1, 0, 1, 'utf-8');

// set $static = 0 or 1, if PHP FILTER can see this then can filter discount products
if ($var2=="-") { $static = "1"; echo "DISCOUNT!"; } else {$static = "0"; }

?>

PHP FILTER CODE

// all 4 variables gives output nothing
dpm($row->_field_data['nid']['entity']->field_commerce_price[0][rendered]);
dpm($data->_field_data['nid']['entity']->field_commerce_price[0][rendered]);
dpm($data->field_commerce_price[0][rendered]);
dpm($static);

if ($static=="1") { return FALSE; } else { return TRUE;}

So how PHP field send a string to PHP FILTER??? OR
Is there any to create a filter function using the PHP FIELD?


texts: How to "featurize" customizations to Answers module (or a content type that is part of a module)

texts:
I'm implementing a discussion feature using the Answers module. I want to create a feature for all the customizations so I can implement and deploy using the git process.

The views and content types that I've customized (answers and questions) are not showing up as options to include in the feature.

Has anyone else worked with this module with git for local, staging/testing and production? How did you push your customizations? Thanks!

Drupal 7.54; Answers 7.x-4.0-rc2

Edit: Answers is a contributed module that comprises of some views and some content types and possible other components.

Edit 2: I've followed the advice in this SE post regarding a similar situation in views, but it doesn't solve my issue with content types or having to basically re-create the module.


texts: Why are URLs with non-existing subdomains not triggering an error 404?

texts:
One of my websites ignores random subdomains. The site doesn't have any subdomains but it will happily accept URLs such as fjiddifjdskdjf.example.com or dsfkljsdflsdjfds.example.com.
In both cases, it will display the home page. Similarly, I can log in at sfkjsdidisfdj.example.com/user.

At first, I suspected the problem was with a .htaccess file I put in the root directory. The file is used to redirect URLs that changed when I redesigned the website. It's got entries like this.

RedirectMatch 301 ^/2012/06/$ /blog/201206

However, after renaming the file, it's still accepting these odd, random subdomains.

I've also checked another Drupal site I maintain. On that site, entering a non-existent subdomain results in an 404 error. I've compared both sites' standard .htaccess files and they're identical. Both sites use the same (shared) hosting package, which should rule out differences in how the server has been configured.

Why URLs with non-existing subdomains don't trigger an error? How can I correct this behaviour?


texts: How can one add superscript character like TM or Reg on a block title

texts: I was wondering how to add superscript characters like trademark to Drupal block title.


texts:
I am wondering if it is possible to stack two ajax_command_replace commands. In other words, to have code that looks like this:

$commands = array();

$commands[] = ajax_command_replace($selector1, $data1);

$commands[] = ajax_command_replace($selector2, $data2);

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

and then to expect both commands to run?

When I try this, the first command runs just fine, but the second command does not. I have reversed the order of the two commands, and sure enough, the (new) first command now runs, but the (new) second command does not. I have also looked at the page after the ajax_deliver has run, and the first command did not destroy the html on the page, so the second command's selector is still there. I have also added a dummy ajax_command_alert just to be sure that I can run multiple commands, and that works as well.
An added comment:  If you use ajax_command_replace, you lose the tags on the selector you have chosen.  Two options to get around this are (1) Use ajax_command_html (which retains the outer tag) or (2) include the outer tag information in the html for the ajax_command_replace.I still, however, cannot stack two ajax_command_replace or ajax_command_html commands.


texts: Best way to modify views output with a custom function?

texts:
I have view with a block display that shows user profile info and the user's points (from user point module). I want to show the "point level" which is a text string based on the number of points the user has.

How do I add that to the block?

I already have a custom function that returns a text string based on the number of points.

I don't want to use views_PHP anymore because it prevents caching of the block.

Should I use hook_block_view_alter()?


texts: Unzip a file in Drupal 7 Form API and upload extracted files

texts:
I'm creating a custom form using Drupal 7 Form API, and I need my users to be able to select a ZIP file containing a number of other files. I'd like to be able to extract the files and then upload each individually, rather than uploading the zip file. I also need to ensure that all files within the zip file are of the correct type. This is my current attempt:

First I created the form:

function form_example_upload_files_form($form, &$form_state) {
  $form['file'] = array(
    '#type' => 'managed_file',
    '#name' => 'files[]',
    '#title' => t('Upload Files'),
    '#upload_location' => $form_state['values']['upload_path'],
    '#upload_validators' => array(
      'file_validate_extensions' => array('xls xlsx txt zip'),
      'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
    ),
    '#process' => array('form_example_my_file_element_process')
  );

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

  return $form;
}

Then I created the submit function:

function form_example_upload_files_submit($form, &$form_state) {
  $file = file_load($form_state['values']['file']);
  $uri = $file->uri;
  $path_parts = pathinfo($uri);
  if ($path_parts['extension'] == "zip") {
    $path = explode("/", $uri);
    $new_path = "public://".$path[2]."/".$path[3]."/"; //This gives the upload file path

    $archiver = archiver_get_archiver($uri);
    $extracted_files = $archiver->listContents();
    /*Remove files with incorrect extensions from the archiver*/
    for ($i = 0; $i < count($extracted_files); $i++) {
      $parts = pathinfo($extracted_files[$i]);
      if ($parts['extension'] != "txt" and $parts['extension'] != "xls" and $parts['extension'] != "xlsx") {
        $archiver->remove($extracted_files[$i]);
      }
    }

    /*Extract all remaining files*/
    $archiver->extract($new_path);
    if (file_exists($uri)) {
      file_delete($file); //Delete the original zip file from the directory
    }
  }
}

The issue that I'm having is that the extraction and deletion are not occurring. The correct files are being removed from the zip file, as seen when I download and unzip the file. If I comment out the remove section but leave in the extract and delete section the zip file is correctly extracted and then deleted, but all files regardless of extension remain.

Does anyone know how to fix this issue? I'd really like to be able to unzip the file prior to uploading and then only upload files with the correct extensions, but I'd be fine with just extracting the files correctly. Thanks!


texts: Only one organic group id / name is shown in content listing

texts:
I want to create a block/page with a general content listing of all the content in the different organic groups.

Problem is the specific nodes only show one group id / group name even though it belongs to multiple groups.

To show the group name I used 'OG membership: Group Node from OG membership' relation.

Is there a way to do is with basic view functions. I suppose it can be done using a PHP field but I prefere the basic methods if they exist.


texts: I created a view of a page and a block, but cannot find either. Where are they?

texts: I created a page view, but when I type in the address for it, it shows "Page not found". When I try to put the block where I want it to go, it doesn't show up, not even under disabled blocks. What step did I miss?


texts: views display restricted number of results based on nid

texts: Is it possible to create a view which would show only 3 rows. Based on curent node (nid) show result before current row and show one row after this row.


texts: Using Migrate API with a multi-page / paginated source

texts:
I have a working module pulling a JSON feed into Drupal 8 using the Migrate API. However, the feed is paginated, and I am only getting the first page of results.

For example:

{
    "meta": {
        "count": 58964,
        "next": "http://api.example.com/endpoint/?page=2",
        "previous": null
    },
    "data": [
        {
            "id": "id:1",
            ...
        },
        {
            "id": "id:2",
            ...
        },
...

I need to go through all pages import them all, but I can't see how to tell Migrate to iterate through the pages.

One option is to use a two-step process: first download all the data to a local file and then import that into Drupal. It would be nicer if Drupal 8 Migrate API could fetch and import all the pages itself.


texts: How to use a sub-domain for a specific content type?

texts:
I have a blog content type. My client would like the domain to be blog.example.com for only that content type. I would like to know the best way to approach this, whether it be a rewrite rule or using Domain Access Module.

I have installed the Domain Access module, and created my primary domain (example.com) and another domain (blog.example.com) for the blog - but am now not sure how to go about assigning that domain for my blog content type.

Any advice is much appreciated - please keep in mind this is for Drupal 8.


texts: How to access the fields in the comment reply page?

texts:
I'm using Drupal 7.

I show the form of comments in a page different from that of the nodes.

In this page, having for url mysite/comment/reply/..., I would like to modify the fields of the node which appear before the form of comments.

For example, the page looks like :

        Add a comment
-
        Title of the node
        Field 1 of the node (display)
        Field 2 of the node (hide)
-
        Comment form

I tried to create a specific page template : page--comment--reply, but I have no access to fields and cannot thus change their appearance.

Do you know how can it be done?


texts: What is a "fluid" column in Display Suite?

texts: What is "fluid" in Display Suite?  I want to create a two-column layout, with a 25% left and 75% right.  Is the fluid 2-column layout what I want?


texts: populating field A with content of field B

texts:
I have a content type with several fields, e.g. phone1 and phone2.

I would like to populate another type of field, "table_field", with values from the first two automatically, on creation of an instance of this content type.

What would be the best way? Can I utilize tokens to do this? Thanks for your time, I appreciate it. This is my first project. Huge learning curve, and am enjoying it.


texts:
I have a form that is used to trigger a bulk operation and add a node for each of the currently registered users on the site. This is all working well, but I'd like to pass form data from BulkAddForm.php to the batch operation in BulkAddNode.php

If is were to setup a variable called $year in BulkAddForm which contained form state. How would I then use it in a line like this...

'title' => 'Perf-plan-' . $year . '-' . $user->get('field_user_employeeid')->value,

BulkAddForm.php

<?php
 namespace Drupal\create_perf_plan_for_new_year\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
/**
 * Class BulkAddForm.
 *
 * @package Drupal\create_perf_plan_for_new_year\Form
 */
class BulkAddForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bulk_add_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['perfPlanYear'] = array(
      '#type' => 'textfield',
      '#title' => 'Year Tag (1819 for instance)',
    );
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Create new Performance Plans'),
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $uids = \Drupal::entityQuery('user')
      //->condition('type', 'batch')
      ->sort('created', 'ASC')
      ->execute();
    $batch = array(
      'title' => t('Bulk Add happening within the Bulk Add Form file...'),
      'operations' => array(
        array(
          '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAdd',
          array($uids)
        ),
      ),
      'finished' => '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAddFinishedCallback',
    );
    batch_set($batch);
  }
}

BulkAddNode.php

<?php
namespace Drupal\create_perf_plan_for_new_year;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Drupal\Core\Url;

class BulkAddNode {

    public static function bulkAdd($uids, &$context){
    $message = 'Bulk add happening in functional file...';
    foreach ($uids as $uid) {
        $user = \Drupal\user\Entity\User::load($uid);
        \Drupal\node\Entity\Node::create([
            'type' => 'perf_plan',
            'title' => 'Perf-plan-' . '1718' . '-' . $user->get('field_user_employeeid')->value,
            'uid' => $user->id(),
            'field_employee_uid' => $user->id(),
            //'field_supervisor_uid' => $user->get('field_supervisor')->first()->getValue()['target_id'], //Brilliant means of getting entity reference UID from User. SM
            //'field_director_uid' => $user->get('field_director')->first()->getValue()['target_id'],
          ])->save();
    }
    $context['message'] = $message;
  }

function bulkAddFinishedCallback($success, $operations) {
    if ($success) {
      $message = 'Performance plan added.';
    }
    else {
      $message = t('Encountered an error during bulk performance plan creation.');
    }
    drupal_set_message($message);
  }
}


texts:
I'm starting with Drupal and I would like to have one instance of Drupal on my dev plateform with each project in a subfolder:

I don't want to have to change my host (and my customers hosts)
I need to keep drupal in a subfolder on my domaine (mydomain.tld/drupal)

Every website should be accessible like this :

mydomain.tld/drupal/customer1.com
mydomain.tld/drupal/customer2.org

I know that I have to add some configuration in sites/sites.php and I tryed:

$sites = array(

    'mydomain.tld.drupal.customX.com' => 'customerX.com'

);

But it looks like the rule is not used and I have a not found error...

Could you help me with that?


texts: Create a view of the 'Recent Log Messages'

texts:
I would like to give an admin user (not User 1) permission to see the Recent Log Messages (/admin/reports/dblog), but I only want him to see 'User' logs. As it is a subscription website he could see who has been signing up and cancelling their accounts. But if I was to give them this permission, they will also be able to see all the other log messages, which I do not want them to see.

I have searched for a module that allows permissions by Log Type (access denied/cron/page not found/etc.) , but with no luck. My best idea is if there was a way to create a View of the recent log messages, I could then create a filter to only show User messages.

Is there a module or some hook where I can limit a users access to 'Recent log messages' by 'Type'?


texts: Set custom cache expiration time for a block

texts:
When returning info for a custom block we can specify what kind of caching that will be used for the block according to the values in: hook_block_info().
Notice that if the block is cached the hook_block_view() will not be called at all.
In a module I'm developing I would like the user to be able to set the expiration time for the block cache, so I have tried something like this:

/**
 * Implements hook_block_info().
 **/
function CUSTOM_MODULE_block_info() {
  return array(
    'custom_block' => array(
      'info' => t('Custom Block'),
      'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

/**
 * Implements hook_block_configure().
 **/
function CUSTOM_MODULE_block_configure($delta = '') {
  $form = array();
  $form['custom_module_cache_expire'] = array(
    '#type' => 'textfield',
    '#title' => t('Cache expire'),
    '#default_value' => variable_get('custom_module_cache_expire', 0),
  );
  return $form;
}

/**
 * Implements hook_block_view().
 **/
function CUSTOM_MODULE_block_view($delta = '') {
  $block = array();
  if ($delta == 'custom_block') {
    $cache = &drupal_static(__FUNCTION__);
    if (empty($cache)) {
      // Try to get data from cache.
      $cache = cache_get('custom_module');
      if (!empty($cache->data)) {
        // Check the expiration time.
        if (time() > $cache->expire) {
          // Remove the cache.
          cache_clear_all('custom_module');
        }
        $block = $cache->data;
      }
      else {
        // Build the renderable array and cache the result for 5 minutes.
        // The 'custom_module_get_items()' is a long running task and
        // the reason why we want to cache this block at a certain interval.
        $block['content'] = array(
          '#items' => custom_module_get_items(),
        );
        cache_set('custom_block', $block, 'cache', time() + (60 * 5));
      }
    }
    else {
      $block = $cache->data;
    }
  }
  return $block;
}

The above almost works as expected, but I was wondering if there some better way of doing this.

In Drupal 8 we can use the cache max-age to achieve this behavior.

I also tried to set the cache in the renderable array for the block, but I'm not sure what this does actually:

$block['content'] = array(
  '#items' => custom_module_get_items(),
  '#cache' => array(
    'expire' => time() + (5 * 60),
  ),
);

Perhaps the best way would be to simply set the caching to DRUPAL_NO_CACHE for the block and then in custom_module_get_items() use cache_set() and cache_get()?

I was also thinking that another way of doing this might be to just remove the default block cache from the database at a specific interval?


texts: Getting the rows that causing error or fail in Migrate

texts:
I am migrating a large csv file into drupal. I am able to do mapping and import the content into Drupal. However, I found it is difficult to get the specific record to that fail. I would be grateful if you could help me on this.

Kind Regards


texts: After altering form I cannot save changes in nodes

texts:
In drupal 7:
I have Answer content type and alter the form for that type:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'answer_node_form') {
    // disabling some fields (ie. #access title field to false)
    // setting defaults values
    // adding one hidden field (that shouldn't be inserted into database)
  }
}

A when I'm trying to submit edit form, the process of PHP takes too much time and Apache restarts.
Do you have any idea what is wrong? Maybe when I send the form, it shouldn't have any additional fields?

I could paste the code but I think it's insignificant.


texts: looking for a complete documentation for Drupal's database schema - need to have some overview

texts:
well dear buddies,

i am pretty new to drupal. Just set up a drupal commons

now i 'd like to add some data to my drupal, and i dont really understand the database model/scheme. Can somebody point me to some documentation? For example i need to understand the role of node, vocabulary, and all the tables and what is tid,vid,nid fieds... Then i could add data the sql way.

Of course I don't think complete documentation for Drupal's database schema exists. Well does any body have a  very very first attempt:

An ongoing attempt with comments for Drupal 6 can be seen here
http://drupal.org/node/79874

An analysis with SchemaSpy i found here
http://webdevgeeks.com/schemaspy/index.html

and overview i have seen here.
http://upsitesweb.com/sites/upsites.co/files/drupal7_model_0.png

well who can give more hints - i love to hear from you -
Again: i want to have some overview on the options i have to extend the group
(running on http://www.schulcenter.org - and see here http://schulcenter.org/?q=group/schulen )

How can i configure / extend the groups (/on the database-level)?
How can i configure / extend the groups (/on the database-level)?

i wanna creat the following fields - (derived from the following shedule https://scraperwiki.com/scrapers/austrian-schools/ ) see the names of the collumns

name
adresse
schultyp
homepage
ergänzender schulname
beschreibung
schwerpunkte

can this be done best in groups !? Can i this set in the groups. Or should i do that in the so called - organic-groups

Note: as you see the site schulcenter.org should give an overview on schools
with a certain amount of data from the profile: the adress, the website..

a little image (a thumbnail of the website - shown in a block,)
a little description (approx 200 characters) what the site /the school does - some special programmes or something like that...

How to achieve this !? Love to hear from you any and all help will greatly be appreciated

love to hear from you
zero


texts: Forcing OpenID login instead of Drupal own authentication

texts: Is there a way to force the users to use OpenID (e.g. Google, Facebook, Twitter) and not use Drupal's internal authentication?


texts: How to display the views page title in a custom fieldable block

texts:
Goal:
To create a custom fieldable block as available out of the box in D8, which also shows the page title of a a views page, if the page it is displayed on is a views page.

I created a custom block type, and added an image field for the block background.

I then copied and modified the block template to include:

{% if title %}
  <h1>{{ title }}</h1>
{% endif %}

But the views title does not show up. The page source shows nothing rendered. I enable theme debugging and the new block template is being used.


texts: Omega override simple-layout.tpl.php for content types

texts:
I have copied the simple-layout files and customized, the custom layout is simply mats2015.simple-layout (mats2015.simple-layout.tpl.php). I need to override this file for a specific content type (plain-page).

Before Omega 4 (and using the layouts extension) I would use the following:

In theme_alpha_preprocess_html(): $variables['theme_hook_suggestions'] = array('html__plain_page_wrapper');
In theme_alpha_preprocess_page(): $variables['theme_hook_suggestions'] = array('html__plain_page');

And, together, those two template files (html_plain_page_wrapper.tpl.php, html__plain_page.tpl.php) would simply render $page['content'] and nothing else.

If, within mats2015.simple-layout.tpl.php I include get_defined_vars() I see this:

'omega_layout' =>
array (size=7)
  'name' => string 'mats2015.simple' (length=15)
  'path' => string 'sites/all/themes/mats2015/layouts/mats2015.simple' (length=49)
  'file' => string 'sites/all/themes/mats2015/layouts/mats2015.simple/mats2015.simple.layout.inc' (length=76)
  'info' =>
    array (size=4)
      'name' => string 'MATS 2015 Simple' (length=16)
      'description' => string 'preview = preview.png' (length=21)
      'template' => string 'mats2015.simple-layout' (length=22)
      'regions' =>
        array (size=11)
          ...
  'theme' => string 'mats2015' (length=8)
  'attached' =>
    array (size=0)
      empty
  'template' => string 'mats2015.simple-layout' (length=22)
  'theme_hook_suggestions' =>
    array (size=0)
      empty

So, the question is: is there a preprocess hook I'm missing that I can use to switch from mats2015.simple.tpl.php to some-other.tpl.php based on content type? Or is there a naming convention for the layout extension files that I'm missing?

Thanks!


texts: In a View, does the order of pages/blocks/attachments matter? & Why isn't my block showing up?

texts:
Views 7x3x:
I have two pages & a block in my view in this order:

[Page1] [Page2] [Block1]

Page1: path/%
Page2: path%/%
Block1: (no path)

I have the same contextual filter on all three, Page2 has a second contextual filter. My block is not appearing as expected. I have the block in the proper region without any restrictions in the block configuration.

In the contextual filter for the block, I've set it to hide the view if the value isn't present in the url. In the view preview, arguments produce results as expected. However in the live view, nothing shows up. (I'm providing the same filter arguments in the url)

When I change the contextual filter to display all results when filter value is NOT available, everything works as expected, but this isn't the behavior I want.

What else could be hiding my block/view?
Does the lack of a path for my block mean it can't see the argument?


texts: How to get the value of a custom field in hook_node_presave?

texts:
Using hook_form_alter I have added a custom field in my node creation form

function custom_assignments_form_alter(&$form, $form_state, $form_id) {
//print_r($form_id);exit;
if($form_id == 'node_assignment_form'){

    $lecture_options = array();
    $lecture_values = db_query("SELECT nid, title FROM `node_field_data` WHERE nid IN (SELECT entity_id FROM
                        `node__field_module` WHERE bundle='lectures' AND field_module_target_id=:tid)",
                        array(':tid' => $selectedWeek))->fetchAll();
    foreach($lecture_values AS $key => $value){
        $lecture_options[$value->nid] = $value->title;
    }
    //print("
");print_r($lecture_options);exit;

    $form['field_after_lecture']['#access'] = FALSE;
    $form['field_after_lecture_tmp'] = array(
            '#title' => t('After Lecture'),
            '#required' => true,
            '#type' => 'select',
            '#options' => $lecture_options,
            //'#default_value' => print_r($form_state->getBuildInfo()['args']);exit;,
            '#weight' => 100,
            '#prefix' => '
',
            '#suffix' => '
'
    );
}}

How to get the value of field_after_lecture_tmp in hook_node_presave
I printed the node fields using $node->toArray() function. But this field is not there. In Drupal 7 I was able to access it.


texts: How can I get my RSS feed to be Auto Discovered?

texts:
Created an RSS feed in Drupal 8 using Views.  The feed is fine, but yet I don't have the discoverability icon show up in browsers.  Looking at the HTML source I don't see anything like this at all

I found this answer for Drupal 7 but doing "Feed Settings > Attach To > Master" had no affect.


texts: How to create a read-only flag that can only be used by an admin to actually flag nodes?

texts: Long story short, I installed Flag because Best Answer was not working properly.  Is it possible to configure flags so that only the admin can flag something (aka an answer as being approved) but everyone can view the flag?


texts: How can I change the  on a View filtered by NID so that it is the referenced Node's Title field?

texts:
I have a view which only displays a single result and I am using NID as the contextual filter. I cannot change that, it needs to be NID.

I want my page <title> to be the "Title field" of the node that was filtered rather than its NID.

As it is, in my contextual filter I can "Override title" by typing in "%1" which results in the terrible <title>1234 | My Site</title>. Assuming node/1234 is titled "John Doe", I want my title to be <title>John Doe | My Site</title>.

How can I accomplish this?


texts: When I disable the poll module my add content page doesn't work. Why?

texts: Im on d7. I no longer want to have a poll on my site. For some reason when I disable the poll module, the add content page becomes blank and says I have not yet created any content types. I have three other content types on my site and they display fine in the admin panel, just not on the node add page. Anyone have any suggestions? Thanks.


texts: Drupal 8 - Bootstrap paragraphs not rendering color and width classes

texts:
I have installed bootstrap paragraphs module and when setting the color and width to the "Simple" bundle or any default bundles that comes with "Bootstrap Paragraphs" the classes are not being rendered on the div.

Please see image below: The classes should have been added to the wrapping div.

This is how the source looks like for this paragraph.

Am I missing anything?

Thanks in advance.


texts: Users can post new node but ONLY Unpublished status

texts:
As the title says, users are able to create new node (type QUESTION), but they can not publish it. The node is saved when the user hits save, but the status is set to unpublished under Admin > Content.
I have checked a few permissions the authenticated user which has:

Question: Create new content
Question: Edit own content
View published content
View own unpublished content

This content is NOT using workflow moderation.


texts: How can I consistently see the "renderable" version of a views field?

texts:
I created a custom views style plugin. I currently use:

$value = $view->field[$label_column]->getValue($row);

to get the value of the field. However, I was recently informed that this does not work for list fields(like 0=>'yes'=, 1=>'no'). This original line displays 0 and 1 instead of 'yes' and 'no'. This user suggested I use:

$items = $view->field[$label_column]->getItems($row);
$value = $view->field[$label_column]->render_item(1, $items[0]);

It seems like this solution does not work on standard fields. I also recently found that the original line does not respect field rewrites. Is there a universal way to see the field value after rewrites, while also respecting lists?


texts: How to display all images from all entities with alt attribute?

texts:
I have a problem with viewing all the images uploaded to the site.

I need to show images that uploaded to nodes, terms, bean blocks. They are using different image fields, so that means that they use different tables. I could use views and show files filtered by mimetype, but the problem is that I need also to show alt attribute and a link to the content this image related to whether it is a node or term or bean block


texts: How can I make a View that shows the number of nodes attached to per taxonomy term?

texts:
I want to list taxonomy terms to see how many nodes are attached to each term.

I made a taxonomy View but can't find a field for the number of the nodes attached to per taxonomy term.

There is no this kind of field by defualt and maybe Views PHP or Views Custom Field are the way to go ??


texts: Commerce product with customer defined attributes

texts:
Is it possible to create a product, for which before adding to the cart, customer must define some attributes. For example, I need a number field where the customer defines the size of the product (105x200mm, or 1000x600mm). There are no predefined sizes, I only need an empty text field for width and height where the customer can type their specific size.

After that I want to add it to the cart but without price. I only want to collect customer orders where the products have sizes. Information about final prices will be sent later by email. We don't want to display prices and no payment.

Thanks a lot


texts: how to save checkboxes values in node programmatically

texts:
i want to save checkboxes values in entity reference checkboxes field with node_save
:

   $form['wrapperrr']['id_offre'] = array(
        '#title' => t('Liste des Offres'),
        '#type' => 'checkboxes',
        '#options' => $optionsoffres,

    );

and into the submit button :

$node->field_entity_reference['und'][]['value'] =$form_state['values']['wrapperrr']['id_offre'];


texts: Edit field in contentType B when creating or editing node of contentType A

texts:
I need to edit a field in contentType B when I create or edit nodes of contentType A.

I know it's possible to use rules for this but I need to have more control so I want to do it in my own module.

Tried this code without success:

function MYMODULE_node_presave($node) {
    MYMODULE_change_value($node);
}

function MYMODULE_change_value($node) {
    $node = node_load($node->nid);

    $referenced_nid = $node->referenced_node[LANGUAGE_NOE][0]['target_id']

    $referenced_node = node_load(referenced_nid);

    $referenced_node->my_field[LANGUAGE_NONE][0]['value'] = 12345.0;
    node_save($referenced_node);
}

Am I choosing the wrong hook?


texts: How do I hide one word from a view result column

texts:
I have a view which displays content overview using a table. I have joined two columns, a and b, in the table.

I want the column to display like the red square... currently they show as the red ellipse. Column a is "moderation state" and column b is "publish time".


texts:
I'm new to Drupal, and I'm attempting to add an image style to a Basic Page in the "Manage Displays" area. After savings, there is no effect with the images on my basic pages (i.e. the image style was not applied) What would cause this, and how can I fix it?

Thanks! (PS - I'm sure this is probably a novice question.)


texts: How to order nodes with a number like 1.1.1

texts:
I have a long list of files to be downloaded with different categories.

So I created a node for each file.

And assigned a term field for the categories

A file can be used in different categories so I cant sort by posted date or the order might be wrong.

Is it possible to create a text field on nodes and then order them in a view based on that number? Example

1.1.1
1.1.2
2.1.1
2.1.2

Views Natural Sort might work for this but I can only get it working on titles.


texts: Printer, email and PDF - can I use this module to print Views?

texts: I have installed Printer, email and PDF and I am happy with the way it renders nodes.  I was wondering if there was a way for it to print views too.


texts: XHProf not displaying runs but empty table

texts:
I'm trying to profile a drupal website using xhprof. I manage to install it and configure drupal to use it (using the devel module) but I have a problem to visualize the result.

First, for some reason I didn't manage to get the access rights to xhprof_html through apache. Instead of using apache I just cd into xhprof_html directory and run php -S myhost:8080. I can then see the main page with all the runs, but when I select a run, it's empty. I can see the table and everything but there is no functions displayed. When I look at the run with a text editor it seems ok.

What am I doing wrong ? Is there another tool to visualize xhprof runs ?


texts:
I am trying to programmatically create a content type with 2 fieldsets, where the second one have an "Add more" option to create multiple set of fields. I looked for a working example to create multiple sets of fields, save, and edit them. Unfortunately, I couldn't find any. My module is creating, editing and saving the content type without 'add more' option.

Can anybody help?


texts: How to get changes in database done by someone else?

texts:
We are working on features in team. My team-mate have done some changes & synced the cloud database.

I also have some database changes locally, now I want those changes in database which he synced.

I can't use drush sql-sync becauses it asks to drop all the tables. So my local changes will gone.

what should I do?


texts: Calculate percentage between two entity fields in Drupal using Computed Field Module

texts:
I am trying to calculate a % of two entity fields in Drupal 7 using Computed Field module.

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_accounts_payable_bs'))) /
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_customer_deposits_bs')));

Display:

$display_output = number_format($entity_field_item['value'] , 1 , '.' , ',');

Current the value I get is ".20" But I want it "20.0"


texts: How do you display all the tpl.php template files that are being loaded on the current page?

texts: Is there a function to show all the tpl.php template files being loaded on the page? Also showing the overrides too. I'm looking for a specific tpl file, but i have hundreds of the same tpl file that all have the same code and I'm not sure which file is the correct one.


texts: Can't get CKEditor to work on Drupal 7.8

texts:
I've tried both the CKEditor module, as well as the WYSIWYG module (with CKEditor library installed). I've configured it all correctly and it should work, but it doesnt. I've also tried changing the CSS options but still nothing.

I'm getting "r is undefined" in the console, but only if I change the text format option underneath where the editor should be.

I'm currently working off localhost - might that be an issue?