texts:
I have a cookie question in regards to a security scan (via IBM Rational AppScan) conducted on a drupal(7.43) site. The security scan failed with the following error: (Permanent Cookie Contains Sensitive Session Information) is POSITIVE on: http://site-name/user/login?ModPagespeed=noscript (cookie = SESSa020b17496f7fb76f92dd28c8d8341be).

How to resolve this?


texts: How to programmatically get the NID of the current node

texts:
I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way.

And solutions like

global $node;
$nid = $node->nid;

don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates $node with a NULL value.

It feels like there must be something really obvious that I'm missing.

So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?


texts: Configure CKEditor - WYSIWYG HTML editor

texts: What is the way to configure CKEditor - WYSIWYG HTML editor for Drupal 7 sites?


texts: Drupal cannot generate the derived image ANYMORE?

texts:
OK, My situation is really complicated (or Im stupid).
I start my website http://rlsgame.org with Drupal System (even if Im .NET developer)...
After 3 month, my website start grow up (about 2000 article and 3000 members) But a problem appear !!! I didnt touch anything, It appear just like that !!

When I want submit a Node, I have an issue with Images, I cant see the preview image :

and After submiting the Node, here is the result:

I refresh the page and the nothing, But after i press CTR+F5, the article is fine:

you can check the page here: http://rlsgame.org/PC/Games/ArmA-III
All is fine...

But the big problem is that Drupal System cannot generate the derived image of User Picture !!
Even if I press CTR+F5 like before, the problem is still here, look an exemple of a profile page:

Link: http://rlsgame.org/users/gamer

The old users profile is fine, because the picture is generated before the problem, exemple:

Link: http://rlsgame.org/users/mgs

And one more thing it start to appear too, Drupal start Caching comments (not like before this problem), when I post comment, sometimes it apear without Caching, and sometimes I must wait about 10 sec, for exemple, I post a comment and nothing appear, and I navigate to the homepage, and here we go, the msg appears:

I think if I fix the issue, All those problems will disappear ...

Im looking for fixing that 10 days ago, So Just for info:

All files permission Are OK:
sites/default  => 555
sites/default/files  => 755  (and all sub-folders too including styles)
And paths of File system are OK
Drupal is updated to 7.26 (latest version)

And the problem is not from the server (Im working on Shared Server) because I downloaded my website and run it in Local but I see the same problem plus My website work before so the problem is not from the server.

Ah, one thing, when i check Reports Log, I see a lot of warning, here is an exemple:

Thats all, plz help me to fix that, Im losing traffic....

Thanx for advance.


texts: Auto pulling an image from a post in Views

texts:
I'm creating a custom view and I want to create thumbnails for the posts.

The problem is there is hundreds of posts and they all have 1-2 maybe 3 images in them. I want to pull the first image in the post and use it as a "post thumbnail" in a view.

Is this possible?

Thanks for any tips.


texts: Changing a redirect depending on selection

texts:
Using drupal 7 how can I make a selection alter where a page is then redirected to ? I need the value selected by a drop down menu to be part of the destination url for the redirect.
For instance if I had the following for a drop down menu:

$form['changethis'] = array(
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),

Selecting option 'two'would send the page to www.mypage.com/two

Any help would be great I have experimented with an ajax request and hook_menu_alter , but no luck so far.


texts:
I have a select list in a view that filters the view by the team number.
Each team number will be displayed in the select list like:
2014-2015 - 01, 2014-2015 - 02 and so forth.
All I want are the last two numbers to display on the view's table, so what I did was used a computed field to just grab the last two numbers so then only the team number shows up.
However, I can't use a computed field to automatically fill the contents of a select list, and when I create a team filter, the select list has  2014-2015 - 01 , 2014-2015 - 02, and so forth.
I want to edit the select list so it only shows 01, 02, etc.
I am really good with JS injector and prefer to do most things like this with that, but sadly the page is refreshed so many times it's not a good thing to use.  Any thoughts?


texts: Hosting Multiple Domains seamlessly with same site code, theme, modules, data etc. not a multisites situation!

texts:
I would like to use D7 to support two domains with same code, themes, modules and even database and content, completely transparent to the end-user.

So, user of oxustech.com would see only oxustech.com and user of oxustechnolgies.com would see only oxustechecholgies.com (not be redirected to oxustech.com).

We don't want to use forwarding/frame forwarding. because frame forwarding will hide the full url and will show every url as oxustechnologies.com only.

The site is under shared hosting and we don't have enough permission to change the Apache setting.

Pointing oxustechnologies.com to same htdocs didn't work.


texts: How can I redirect user/*/edit to another page based on user content?

texts: I have a site with the following relationship: for every user, there is one corresponding (node) profile. For the user/*/edit, I would like the user to actually edit their profile node, not the user account. I've thought about preprocessing the page template to make something available in order to then re-write the secondary menu in the template - but which variable can I use? It's not available in the $user array.


texts: Get Video URL from Media Entity reference field

texts:
I have an entity reference field to Media Video.

I'm trying to get the uri to the video file in node template.

Most of the solution I found around is regarding Image/File. But not Video.

Tried Twig Field Value module but it doesn't work.


texts: cache_form has been truncated. Permanent error MYSQL Incorrect key file when a form is accessed

texts:
On a site I inherited, I can see cache_form is empty. It has been truncated some time ago. I have got an error crashing my site when accessing many type of forms: views exposed forms, forms to edit Views and node edit forms. The error is a MYSQL Incorrect key file error and is triggered by clear_cache_all().
There is an attempt to DELETE FROM cache_form, where a given form ID is found. However the table is empty so it does not work.
I do not know why Drupal has to delete a cache entry from the table even for a new node.
Is there a way to bypass the step where Drupal try to delete the cache entry?


texts: How do I show a teaser of external content in Drupal 7

texts:
I want to be able to create a node that shows a teaser from an external page. So the user would create a new node, add a link to the page and then the body would show a teaser of the content from the external website. When the user clicks on the link it should open a separate page or tab and redirect the user to the original content. Similar to what Linkedin and Facebook do when you attach a link for a status update. I have tried the Statuses module and the microblogger modules but they are really buggy. Any suggestions?

Facebook has this cool functionality: when you post something that seems to be a link, it will automaticly parse the linked site and show you

The content of the title-tag

A Teaser of the Text (I don't know how it is able to identify the content area, but it seems to be very reliable)

An Image taken from the site (it present you every img-tag and you can choose witch you want to show)

For example when I enter this site:
http://www.air-watch.com/company/news-room/press-releases/2012/03/flight-options-first-in-industry-to-receive-ipad-class-1-electronic-flight

The title will look like this:

Case Study: Flight Options First in Industry to Receive iPad® Class 1 Electronic Flight Bag Authorization | drupal.org

And this text will be fetched as teaser:

Basic EFB features provide the ability to conduct flight planning calculations and access digital documentation displays such as navigational charts, operation manuals and applications and aircraft checklists.

The image piece is a nice to have but not mandatory. There is a module that will allow me to pull that separately.


texts: Display suite extra expert mode field classes not working on entity form fields

texts:
I'm using display suite extra and trying to ad classes to fields via expert mode, but it's not working, I tried both teaser and full content, am I missing something here?

Using boostrap theme and this works with all content items and fields, but not with entity forms, any idea?

Using D7 with boostrap theme.


texts: Fatal error message after installng drupal

texts:
I get this error message when uploading the site on the server. I really need help.

  Fatal error: require_once(): Failed opening required '/home/mydomain/public_html/includes/drupal/includes/database/select.inc' (include_path='.:/usr/local/share/pear') in /home/mydomain/public_html/includes/bootstrap.inc on line 3160


texts: Rewrite output in a view using CCK fields

texts:
I'm trying to rewrite the output of a field. I have 4 fields and in the last one, I have rewrite output enabled:

[title]

[entity_id_3], [entity_id_1]

[entity_id]

The fields that are included in this output have "Exclude from display" checked so that's not a problem.

The problem is that the output turns into this:

Mr Speaker

Manager, Hotels

,

Hotel Inc.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et libero vel mi fringilla commodo ac ac felis. Proin fringilla tempor diam, ut semper dui vestibulum in. Vestibulum arcu tellus, elementum ac consectetur ac, tincidunt non eros. Nunc tempor ipsum eget erat fringilla tempus ut a enim. Donec posuere luctus mauris id ornare. Fusce at est lorem, et consectetur sapien. Pellentesque ac purus ac augue dignissim aliquet a rutrum turpis.

The fields that are part of the rewritten output are still wrapped in an HTML wrapper or label wrapper. I have no idea how to remove this and display just the field value.


texts: Custom theme function and template suggestion

texts:
I'm trying to create a theme function, with a template:

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
    ),
  );
}

The my-template.tpl.php file is in the module directory and it works, I have added this to my page.tpl.php:

<?php print theme('custom_function', array()); ?>

I've tried to copy that template on my theme, but it doesn't work, Drupal always reads the module template, not the theme.

Have I forgotten something?


texts:
I use wysiwyg with ckeditor, and I was wondering how I would add css styles so a user could, for instance, float images to the left or make other similar changes...?

Thanks!


texts: How can I allow more file extensions with file uploads?

texts:
I've got a module that let users upload files, and everything works as long as the files are in the standard array of allowed extensions. I've tried using file_validate_extensions(), but this doesn't seem to change anything.

This is the code I'm using to upload now (the docx extension is added to the standard allowed ones, but it doesn't seem to get picked up):

$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}


texts:
I am rendering node form on my custom page with such a code:

<?php
 $form_state['build_info']['args'] = array($node);
 form_load_include($form_state, 'inc', 'node', 'node.pages');
 $form = drupal_build_form($type . '_node_form', $form_state);
 return drupal_render($form);
 ?>

I need to add  some custom form elements to the form as follows:

 <?php
  $form['mycode'] = array(
 '#type' => 'textfield',
 '#title' => t('My code'),
 );
 ?>

The custom form elements are displayed correctly in the form. The problem is, when I submit the form, I cannot see custom values in $form_state or even $_REQUEST array.
I am checking $form_state values in the implementation of hook_node_submit

What is the correct way to add custom form elements to node form (except creation of fields) ?
(I need custom form elements because I need to use different field widgets for various user roles. I also need to add checkbox like "I have read Terms and Conditions" into node form.)

thanks
Tomas


texts: Private schema is always used for system.files route

texts:
I am trying to serve files from Amazon S3(s3:// stream wrapper) via system.files / system.private_file_download routes but no matter what I do the scheme is always set to private.

I have tried to use
/system/files/s3/file.jpg for system.private_file_download
and
/system/files/s3?file=file.jpg for system.files

but I always get private scheme.

The system.private_file_download route seems to be completely broken due to htaccess rules(ie. serving image like this won't even make it to the controller) and system.files somehow completely ignores provided scheme argument.

So far I have observed that the routes get matched to requests in exact opposite as one would expect.
The system.files route is defined first and it expects only "scheme" url argument(with "private" as default value in controller and also in the route itself), for example /system/files/public and what is provided as "file" query argument is used as target, so /system/files/public?file=foo/bar.jpg should result into public://foo/bar.jpg but instead the system.private_file_download route is used(even though it is defined after the system.files route). This route expects the "filepath" url argument, like /system/files/foo/bar/.jpg, and it automatically uses the private scheme because both of these routes use the same controller but this route does not provide the scheme in its definition or path so the default value from the controller itself is used.

I think the issue here is that the second route is using the filepath: .+ argument mask and therefore will match "better" with the path so it will have more priority over previously defined system.files route.

Also strangely the "filepath" url argument in system.private_file_download route has no match in the controller(\Drupal\system\FileDownloadController::download) so the resulting uri will be simply private:// no matter what values are provided to the route.

I have replaced the public stream wrapper with s3 so all files are now served from remote server and it is working just fine. I was able to get the image styles working(system/files/styles/thumbnail/public/foo/bar.jpg) but I am still not able to serve the original files from under /system/files path as well. Since  I need to serve the physical files and not File entities, even if I would switch to private file system the files would not be served because file_file_download() handles only file entities.

I have ended up with custom route. If anyone is interested the important thing is to have two routes(just like the two mentioned above). The second one will transform the url arguments into query argument and return path to the first route. This is done via path_processor_inbound tagged service(see \Drupal\system\PathProcessor\PathProcessorFiles).


texts: Feature stuck on Overridden - "Overrides" column empty, "Default" not

texts:
I have a feature which is constantly stuck at overriden, no matter how times I try to revert or re-create it. I have gone through the standard checklist, including uninstalling and reinstalling, and checking the correct includes are present in .info file and .module file.

On the "Review Overrides" panel, however, I have the attached screenshot. Noticed that the default contains an array full of field settings, but the overrides just contains FALSE:

It would seem that my database doesn't contain this info when it should, and refuses to take it from the Feature?

UPDATE:

I checked the .info file and they seemed all in place; however I suspect that the second cause indicated by the accepted answer below could be the problem. There are currently two modules that remain in a persistent "Overidden" state, and they both share: "CTOOLS EXPORT API -> context:context:3" and "FEATURES_API -> api:1". On initial investigation it would seem that these two items are inherent in the feature, although perhaps I could remove the CTOOLS EXPORT API item by removing the ctools dependency? Argh...


texts: View of users with the same 'entity reference' field vale

texts:
I'm running a D7 site where every user profile has a 'entity reference' field referencing to their manager.

All I want to do is to create a list of the users sharing the same manager in context to logged-in user.

Can anyone please help


texts: What function/method should I use for file_directory_path()?

texts:
In Drupal 6, I am using the following code.

$id = fileowner(file_directory_path());

What is the Drupal 8 equivalent of that code?


texts: How do I check by default a checkbox from a checkboxes control after an AJAX call

texts:
I have the next form which behavior is:

When you select an option from select control, different checkbox are load on checkboxes control.
When you check/uncheck checkbox a message is showed on the botton with info about select value and checkbox clicked.

Everything works fine, but is impossible check by default a checkbox from checkboxes control after ajax function.

Any idea?

namespace Drupal\drupal_miseries\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Checkboxes;

class CheckboxesAjax extends FormBase {

    protected $values = [
        'select' => [
            '1' => 'Value1',
            '2' => 'Value2',
        ],
        // Options when select 1 is selected
        'checkboxes_v1' => [
            '1' => 'checkbox1',
            '2' => 'checkbox2',
        ],
        // Options when select 2 is selected
        'checkboxes_v2' => [
            '3' => 'checkbox3',
            '4' => 'checkbox4',
        ],
        // Default values for checkboxes
        'checkboxes_df' => [
            // Default value when checkboxes_v1 is showed
            '1' => ['1' => '1', '2' => '0'],
            // Default value when checkboxes_v2 is showed
            '2' => ['3' => '0', '4' => '1'],
        ],
    ];

    public function getFormId() {
        return 'drupal_miseries_checkboxesajax';
    }

    public function selectAjaxCallback(array &$form, FormStateInterface $form_state) {
      return $form['container'];
    }

    public function checkboxesAjaxCallback(array &$form, FormStateInterface $form_state) {
      $checkbox = $form_state->getTriggeringElement();
      $select = $form_state->getValue('select');

      $form['status']['mensaje'] = [
          '#markup' => 'Select: '.$select.' '.$checkbox['#title'].' clicked.'.'',
      ];

      return $form['status'];
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
      $form['select'] = [
        '#type' => 'select',
        '#title' => $this->t('Select form control'),
        '#options' => $this->values['select'],
        '#default_value' => key($this->values['select']),
        '#ajax' => [
            'callback' => [$this, 'selectAjaxCallback'],
            'wrapper' => 'checkboxes_wrapper',
        ],
      ];

      $form['container'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'checkboxes_wrapper'],
      ];

      $form['container']['checkboxes'] = [
        '#type' => 'checkboxes',
        '#title' => $this->t('Checkboxes form control from select @select',
          [ '@select' => empty($form_state->getValues()) ?
              $this->values['select'][key($this->values['select'])] : $form_state->getValue('select') ]),
        '#options' => empty($form_state->getValues()) ?
          $this->values['checkboxes_v1'] :
          $this->values['checkboxes_v'.$form_state->getValue('select')],
        '#default_value' => empty($form_state->getValues()) ?
          $this->values['checkboxes_df']['1'] :
          $this->values['checkboxes_df'][$form_state->getValue('select')],
        '#ajax' => [
            'callback' => [$this, 'checkboxesAjaxCallback'],
            'wrapper' => 'status',
        ],
      ];

      $form['status'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'status'],
      ];

      return $form;
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {

    }
}


texts:
I'm looking for a module that makes it possible to attach an existing view to a specific node. I've looked at eva, but it seems only to allow connecting a view to all entities of a specific content-type. I wrote my own module, that can do this, and it works, but I would like to use a module that is well tested and maintained. Does anyone have any suggestions?

* EDIT *

I have installed the views reference module and this seems to be what I want, but when I do print_r($content) in my node--type.tpl.php file, the only thing related to this field is the following:

[field_attached_view] => Array (
                        [und] => Array (
                            [0] => Array (
                               [view_id] => products_view:first_display
                               [arguments] => sample/all/jeans
                             )
                         )
                     )

I have managed to load and display the view by something like this:

  $view_id = $node->field_attached_view[$node->language][0]['view_id'];
  $parts = explode(':',$view_id);

  $args = explode('/',$node->field_attached_view[$node->language][0]['arguments']);
  $view = views_get_view($parts[0]);
  $view->set_display($parts[1]);
  $view->set_arguments($args);
  $view->execute();
  echo $view->render();

But, there must be a cleaner way of doing this?

Thanks in advance.


texts: When to use a php function vs a drupal_ equivalent function?

texts:
I come from update my Coder module to the v1.3 and when I go to check one custom module I see the following message:

  Line 71: in most cases, replace the string function with the drupal_
  equivalent string functions

$node_type = substr($form_id, 0, -10);

  Line 187: in most cases, replace the string function with the drupal_ equivalent string functions

$info->language = ($info->language == 'und' || empty($info->language)) ? t('Undetermined') : ucfirst($info->language);

So, why I need to use the drupal_substr() and drupal_ucfirst() in this case? And in general why to use the drupal_ equivalent functions when we have the php functions?


texts: How can my eCommerce site only showcase products without an Add to cart option?

texts:
I want my Drupal eCommerce site to only show products which contain only product name, description, PDF file.

I don't want price & Add to cart options. Is there any possibility in Drupal?


texts:
In the following snippet, the form returned has only the hidden values. No name, email, or comment.

require_once drupal_get_path('module', 'contact') .'/contact.pages.inc';
$elements = drupal_get_form(array('contact_site_form'));
$form = drupal_render($elements);

Can anyone say why $form is not returning an HTML form?


texts: How to override an existing theme without subtheming it?

texts: Does anyone know how to overload/override an existing theme with one's own .css and .tpl.php file, without subtheming it?


texts:
My Drupal 6 site's login function stopped working all of a sudden, with no error other than "login attempt failed".

No database table crash
Cookie domain is not set
Drupal runs in "single-site" mode, not "multi-site"

The copy of the site runs well on my local machine.
Do you have any advice?


texts: hook_page_alter to change title on user profile page?

texts:
Right now I have the following function implemented in template.php:

function ccom_page_alter(&$page) {
  if (array_key_exists('#account',$page['content']['system_main'])) {
    $account = $page['content']['system_main']['#account'];

    if (isset($account)) {
      drupal_set_title($account->field_complete_name['und'][0]['safe_value']);
    }
  }
}

Is this the best way to set the title on a user page?  Or should I be doing this through a different hook?

EDIT: I've updated my template.php to use hook_preprocess_user_profile instead, and I have this:

function ccom_preprocess_user_profile(&$variables) {
  drupal_set_title($variables['elements']['#account']->field_complete_name[LANGUAGE_NONE][0]['safe_value']);
}

The page title changes (like the one the browser shows you on a tab), but the user profile Drupal page title remains the username.  Very annoying.  Still working...

EDIT 2: I ran an experiment.  I did the following:

function ccom_preprocess(&$variables, $hook) {
  dpm($hook);
}

Which gave the following output when viewing a user profile page:

search_block_form
block
region
block
region
user_profile
user_profile_item
user_profile_category
block
region
html
region
user_picture
page

So that's the order in which the preprocess hooks are called on that page.  I then created two functions:

function ccom_preprocess_user_profile(&$variables) {
  dpm($variables);
  drupal_set_title('mytitle');
}

function ccom_preprocess_page(&$variables) {
  dpm($variables);
  drupal_set_title('mytitle');
}

I first loaded the page with the ccom_preprocess_page function commented out.  The title in the browser tab changed to mytitle, but the page title stayed as the username for the user profile page being viewed.

I then commented out ccom_preprocess_user_profile and uncommented ccom_preprocess_page and reloaded the page again.  Both the browser tab title and the page title changed to mytitle.

This tells me that somewhere after the user_profile preprocess hook function and up to and including the page preprocess hook, the page title is reset.  Where that is I'm not entirely sure.

So, my thinking at this point would be to create a global variable and set it equal to the user account object available in the user_profile hook, and then in the page preprocess hook just set the title based on the complete name field available in the account object.  Thoughts?


texts: After adding a column to a module's schema, should the new column also be placed inside hook_schema?

texts:
I have my own module which implements its own schema. I now want to add a column to the table provided by the schema, which I plan on accomplishing via hook_update_N() and db_add_field().

My question is essentially what the title of this question is: after I add the new column to the schema, should the new column also be placed inside the module's hook_schema() implementation? Example (adds a column named mynewcolumn to the schema of the module mymodule):

function mymodule_update_6000() {
  $ret = array();

  db_add_field($ret, 'mymodule', 'mynewcolumn', array(
    'description' => t('This is my new column'),
    'type' => 'text',
    'size' => 'big',
    'not null' => FALSE
  ));

  return $ret;
}

At this point, do I place mynewcolumn inside mymodule_schema()? Or does mymodule_update_6000() fully take care of proper installation and uninstallation?


texts:
I have a quite big website with restaurants. I'm saving their data (like coords, city, street, country etc.) with CCK fields.

Fields City and Country are connected with vocabularies (named Cities and Countries). What i'm trying to do is to somehow bulk save all the Cities terms as a child elements of a term from Cities taxonomy. So if i have a restaurant located in Barcelona, Spain, i wan't to save a Barcelona term (from Cities vocabulary) as a child element of Spain term (from Countries vocabulary).

Have you any ideas how can i make something like this ?
thanks in advance.


texts:
I have a content type called "Business", and a user can have multiple "Businesses".

Each business has a "business e-mail" field. This is different from the users email address, and is different for every business.

I want to be able to use VBO to send an email to all selected businesses. I have the view set up ok, and in the recipients field on the send email page I add the token....

[node:field-business-e-mail]

and I also tried...

[node:field_business_e_mail]

But I still get the error :

  Enter a valid email address or use a token e-mail address such as
  [node:author:mail].

Is there a way to get around this?


texts: Entity Translation Im/Export with image field

texts: I have an CSV with lots of Nodes that I imported via Feeds Module. The fields contain a title, a textfield and an image. I'm using Entity Translation. Now I want to export and import those fields to add an english translation. I can export the textfields but not the image field, they just don't appear in the UI. Is there a solution how I can import the englisch version of my image field?


texts:
Is it possible to delete a file not in usage outside of the context of a field widget in Drupal 8?

I tried to find a route like admin/file/{file}/delete but don't really see anything in the file module to do this operation.

I found this issue, which I assume is related. So the question remains: How can you delete files? I've set "delete orphaned files after" to Never in the admin so that files are not mistakenly deleted, which has happened to me a few months ago.


texts: How to create Poll Question programmatically with multiple answer choices in Drupal 8

texts:
The code below does not create the choices directly.

$poll = Poll::create(array(
  'id' => 'poll',
  'uid' => '1',
  'question' => 'What is your favorite color?',
  'choice' => entity_create('poll_choice', array(
    'id' => 'poll_choice',
    'label' => 'choice',
    'langcode' => 'en',
    'choice' => array('Red' , 'Blue'),  // this line do not help me to create multiple option for choice.
  )),
  'anonymous_vote_allow' => '1',
  'result_vote_allow' => '1',
  'status' => '1',
));
 $poll->save();


texts: Custom field in order not shown on checkout panel

texts:
I just discovered the commerce 2 module.
I create a date field in the order type ( each customer need to select a shipping date when they bought product ).
If  I create the order from the adminstrator interface the field is displayed.
But when the customer use cart to buy a product the date field is not display ?
Can you help ?


texts: How can I reduce the file sizes of the original versions of uploaded image files?

texts:
I have a Drupal 7 site that allows users to upload pictures of themselves.  While the pictures aren't using much space on the server's filesystem now, I am worried that if my membership grows substantially I will have to add more space to cover all the images.

Right now, I allow users to upload images up to 10 MB in size.  I want to leave this limit high if possible because many of my users are not technically skilled and they do not know how to resize their images.

At the same time, the largest resolution that will be used on the site is 1024x1024.  So, I have configured the core image field to automatically scale down the images to 1024x1024.  This significantly reduces the file size.

Are there any other ways to automatically reduce the size of uploaded images?  Please note that I am talking about the original files, not image styles.


texts:
I want to do theming of default user login page.

Can we create a page  similar like page--node--33.tpl.php.


texts: Is it safe to allow domain.com/username?

texts: Are there any security risks if we create pathauto roule so that the user account pages are at domain.com/username


texts:
I want to process some details before saving the node in Drupal 8. How will I get the form ID of the submitted form?

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->getEntityType()->id() // this only prints "node"
}

Is there any other workaround?


texts:
I have a custom slideshow and the phrases are all in page.tpl.php (please see figure attached)
But they are not dynamic, so they are in PT.

Now I have a multilingual site (I installed all the necessary modules) and everything in my site is working great.

My question is: How can I translate those strings in page.tpl.php to English everytime I switch to EN in my site? Does it require much coding?

Thanks!


texts: Where to add my merchant gateway using ubercart?

texts:
I am trying to figure out how to add the gateway of my merchant so I can accept credit card payment.

I have given a URL by my merchant and I can redirect to this URL easily using my own PHP code, but I can't find a way to integrate it using Ubercart.

Example gateway is https://test.mymerchantgateway.com/ECN/eng/payment/payForm.jsp.

So that when my customer checkout it will be redirected to the url above and when the payment is successful it will return to my website using the "successUrl" like:

<input type="hidden" name="successUrl" value="http://mydomain.com/success.php">

I am using Drupal 6, if that makes any difference.


texts: How do I invalidate cache of an embedded view?

texts:
I have a node type "Article" that contains a repeating Paragraphs field. One of the paragraph types let's the user embed a view using a entity reference field. When rendering an Article node containing a views reference I embed the selected view in hook_preprocess_paragraph like this:

$view_id = $paragraph->field_view->target_id;
$view = \Drupal\views\Views::getView($view_id);
$view->setDisplay('embed_1');
$vars['content'] = $view->preview();

This is working fine except when I enable caching. For example one of my views lists nodes of the type "Event". When I add a new Event it does not show up in the listing until I clean the cache. I could force clean the cache when inserting / updating / deleting an "Event" but I would much rather use Drupal 8's cache tag system and only invalidate the cached content that contains event lists. The problem is I cannot get it to work.

So far I have tried adding cache tags to the node, the view, and the paragraph  in hook_preprocess_paragraph and hook_preprocess_node like this:

$vars['paragraph']->addCacheTags(['node_list']);
...
$view->storage->addCacheTags(['node_list']);
...
$vars['node']->addCacheTags(['node_list']);

According to this page node_list can be used for node listings to invalidate the cache whenever a node is updated. But it has no effect. Maybe the preprocess hooks are to late to add cache tags?

What am I missing?

Edit:

After some more testing I found that if I edit an event, the changes can be seen in the listing and if I remove an event it disappears from the listing. The problem only occurs when adding new events.


texts:
I'm using Drupal 6.16. I would like to permanently disable the /blog path (and all its sub-paths, but not the Blog module.

Is this possible?


texts: Suppress certain content types from taxonomy term list display (D6)

texts:
I'm trying to suppress certain content types (blogs) from displaying in the taxonomy term list. (taxonomy/term/*)

I realize that a specific content type can be turned off for a vocabulary but we have hundreds of nodes that have tags defined.


texts:
I need to get the global $user object in Drupal 8.
I did $account = \Drupal::currentUser(); in the definition of getSubscribedEvents() (a static method) inside a class file.

I get the following error when running drush cr:

  exception
  [error]
  'Drupal\Core\DependencyInjection\ContainerNotInitializedException'
  with message '\Drupal::$container is not initialized yet.
  \Drupal::setContainer() must be called with a real container.' in
  /Applications/MAMP/htdocs/drupal-8.0.x-dev/core/lib/Drupal.php:129

What is wrong in my code?


texts: How to import context module export -drupal 7

texts:
I have created a Context using the Context module for use with a custom module.

Is it possible to export a context and then import it with my custom module? And if so, where does the data from the export need to go in my module?


texts: Disable an parent link for dropdown menu but keep css

texts:
i have this menu : http://jsfiddle.net/aL7Xe/1000/

And I disabled the href link "bewerken" with

a[href="/test4/disabled"] {
  pointer-events: none;
}

But now my css does not show on that link, does anyone have any idea on how I can keep my css on that link but still have it disabled ?


texts: I want to create a rule that sends an email to all users of an organic group when content is posted to that group.  In the email I want the name of the group to appear in the subject.  I'm completely lost.  How can this be accomplished?


texts: Views of panel nodes - how can you display a field from one of the panel's nodes

texts:
I've got a view of Panel nodes. I want to display the Panel title in the list, followed by the body field from a particular node contained in one of the Panel node's regions.

Is this possible?


texts:
In admin/config/search/redirect/404, I found a lot of invalid url, it's a lot of additional "products" on our url, for example, News/products/products/products/products/products/products;
LED-Replacement-Lamps/LED-RGB-Lights/products/products/products/products/products/products/products/products/products;

The "NEWS" is our Contents, but "LED-Replacement-Lamps/LED-RGB-Lights/" is 301 redirect I do by "URL redirects”. So I want to know it's the problem of "URL redirect" tool or others?

I have check the patterns,but i did not find the issue.
I want to know why there is many links with additional "product" repeat again and again?


texts: Show filtered list of links based on user profile?

texts:
My end goal is to provide users access to digital files they have purchased. This is for a magazine, so there's 1 per month, with an archive going back for years.

I have been able to import user info via a CSV file, including columns correlating issue number with a 1 or 0. I can display this all in the user profile, but not in any useful way. I can't figure out how to generate custom links: "here it is" for 1 or "click here to buy" for 0. Or a file download. Or whatever.

A lot of modules seem to have something like this functionality, and I've tried a dozen now with scattered progress. Even just being told that one module (or a combination) would definitely work would assure me that my messing around was useful. I am also open to other approaches.

I have experience with PHP+MySQL—I could've coded this by hand pretty easily by now—but I am working for a non-profit. I hope to automate myself out of a job and leave them with something that won't require a programmer to maintain.


texts:
I am baffled by this line of code:

$work[$id] = $view->field[$id]->theme($row);

Does anyone know where theme($row) gets evaluated?

$word[$id] gets set to this emfield's url, "http://mysite.com/myvideo.flv", which is the value of both:

$view->field[$id]->last_render
$view->field[$id]->original_value

So I am guessing that theme($row) gets evaluated to either 'last_render' or 'original_value'.
But when I add debug code to print theme($row), nothing gets printed.

Any ideas?

Here is the context in which this line of code appears, from views-view-swftools.tpl.php:

   foreach ($rows as $key => $row) {

          // Reset the work array
          $work = array();

          // Render each field in this row using the assigned handler
          foreach ($keys as $id) {
            $work[$id] = $view->field[$id]->theme($row);
          }
          ...
    }


texts: I have a url that would normally redirect to a specific page, however, some code is run prior to this. I am returning a RedirectResponse instance, and it appears to be being cached. How can I force this not to be cached?


texts: How to collect and display visit statistics for a Views page?

texts:
I wonder if someone can point me in the right direction for the following:

I'd like to collect and display statistics for a Views page.

I wonder what's the best approach for collecting basic 'hit' statistics for a views page (essentially a visitor counter for that view). The view uses contextual filtering (i.e. nid) to render content. Ideally, each path (i.e. viewpath/12, where 12 is the nid) has separate statistics.

Any guidance is appreciated.


texts:
I'm currently upgrading my site from Drupal 7 to 8 and I'm having trouble with the pagination URLs.
On the Drupal 7 site we use the Clean Pagination module which changes views pagination to be /news/page/2 and so on.
With Drupal 8 the module was never completed and just redirects until the browser drops the connection.
As default the views use /news?page=2.
If I try to hit the old paginated URL on the new site I receive a 404. Obviously, this is not great for SEO when I have so many pages!
Any ideas on how I can implement an updated pagination URL structure?


texts: How do I show the current node title in page.html.twig OR in node.html.twig?

texts:
If I want to show the current node title in page.html.twig (by default it seems to only be available in node.html.twig) I have to create a preprocess function like so:

function theme_preprocess_page(&$variables, $hook) {
  // Set our page title so we can access it in page.html.twig
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['my_node_title'] = $node->title->value;
  }
}

And then I have to overwrite page-title.html.twig by copying it into my current theme folder and commenting out everything.

This doesn't seem "right".  Is there a better way?


texts:
In search results page,

the search form and search results are in the content area.

Can we insert another block between the search form and results list? Or adjust the order for example put "spelling-suggestions" on the top of the form, then add another block between the form and search extra provided by display suite.

If without existing templates, guessing we will have to modify the $node['content'].

Any ideas are welcome, thanks

<form id="search-form" class="search-form" accept-charset="UTF-8" method="post" action="/search/all/test">

One result


texts: Redirect loop only hompage when redirect from http to https

texts:
I am trying to use Varnish + Pound, when using https everything is OK except only hompage has redirect loop. The others page are OK.
Here is my rewrite rule in .htaccess file.

Please help me with redirect loop

 RewriteEngine On
 RewriteCond %{HTTP:X-Forwarded-Proto} !https
 RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,QSA]


texts:
This is for Drupal 6.

I have a module that creates a custom node type called program.
I have a role called "marketing" and it has a permission entitled "edit marketing copy"

I've used hook_access to grant update permissions to users who meet this criteria, but the edit tab does not appear on the content when I view it.

function programs_access($op, $node, $account) {
    switch($op) {
        case 'update':
            if(user_access('administer programs', $account) || user_access('edit marketing copy', $account)) {
                return TRUE;
            }
        case 'delete':
        case 'create':
            if(user_access('administer programs', $account)) return TRUE;
    }
}

I know that the user has the permission because the view template shows specific things based on permissions and those work as intended. I just do not receive the "edit tab"

How do I make the edit tab appear on the page for the user? What am I missing?


texts: Keeping the  part in the CKEditor and removing everything else

texts:
I've naive customers who will need to copy the HTML part of email in Outlook. So I want them to copy and paste the HTML source of the email which includes <html> <body> </body> </html>.

Is there any filter which will remove all but keep only  the content within the <body> part?


texts:
Is it possible to create a view be that a page or block that shows the following.

-Total number of nodes user has created.
-Total number of comments (all comment types) user has posted.
-Total of how many times this user nodes or comments have beed Flaged as HELPFUL. (flag module is used for this)

All this using the path /user/%user/stats

Which means contextual filter user ID value will be provided from url path 2.

I am stuck with the three bullet points above. Or how to calculate the totals for each.


texts: Calculating shipping rate on country not working - finding workaround

texts:
I installed commerce-kickstart 2.0-rc2 and need to set three shipping rates for different countries. I tried it the "obvious way" using flat rates module and rules "Order address component comparison", but it doesn't work. I followed the instructions from http://www.drupalcommerce.org/node/2511 but the comparison mostly fails, sometimes not, no idea why. Don't know if it's an address module issue or rules. It worked for me on an earlier beta release of commerce-kickstart.

So, what I did:

Created three different flat rate shipping services.
Created a calculation rule.
First condition: data comparison (Data to compare: [commerce-line-item:type], Data value: Shipping)
Second condition: entity has field (Entity: [commerce-line-item:order], Field: commerce_customer_shipping)

Now I should be able to use "Order address component comparison", but it doesn't work.
I can dpm in actions for the shipping-line-item and can see the country-code, but I don't find a way to get it compared.

I tried it with "data comparison" rule, but it seems, I can't get deep enough in the array to get the correct field. I can dpm this: commerce-line-item:order:commerce-customer-shipping, and I see the country code here: ->commerce_customer_address['en'][0]['country'], but I don't find a way to use it for comparison.

Maybe there is an easy solution with executing custom php code in rules to compare the countries?

Maybe the problem has to do with field translation. The customer profile types billing and shipping information have field translation on. I tried to disable translation, but after next test order it was enabled again.

Then I checked the database fields for address management and found something strange. In field_data_commerce_customer_address table the language is 'en', but in field_data_commerce_customer_billing and -shipping it is 'und'.

If I switch page language to english, the checkout finishes without error.
If site language is german, the addresses are not shown on checkouts review page, and on complete page I get errors from presave function.

Undefined index: und in commerce_order_commerce_customer_profile_presave() (Zeile 522 von /drupal-commerce/profiles/commerce_kickstart/modules/contrib/commerce/modules/order/commerce_order.module)
Undefined index: und in commerce_order_commerce_customer_profile_presave() (Zeile 523 von /drupal-commerce/profiles/commerce_kickstart/modules/contrib/commerce/modules/order/commerce_order.module)
Invalid argument supplied for foreach() in commerce_order_commerce_customer_profile_presave() (Zeile 532 von /drupal-commerce/profiles/commerce_kickstart/modules/contrib/commerce/modules/order/commerce_order.module)
Undefined index: und in commerce_order_commerce_customer_profile_presave() (Zeile 522 von /drupal-commerce/profiles/commerce_kickstart/modules/contrib/commerce/modules/order/commerce_order.module)
Undefined index: und in commerce_order_commerce_customer_profile_presave() (Zeile 523 von /drupal-commerce/profiles/commerce_kickstart/modules/contrib/commerce/modules/order/commerce_order.module)
Invalid argument supplied for foreach() in commerce_order_commerce_customer_profile_presave() (Zeile 532 von /drupal-commerce/profiles/commerce_kickstart/modules/contrib/commerce/modules/order/commerce_order.module)

Can someone help me with that? Did I do some configuration wrong? Is it a module problem?


texts: Drupal 7 EVA fields not rendered on unpublished nodes

texts: In a node type with 3 EVA fields, if I unpublish the node, the node view tab shows only the pink watermark "Unpublished" and the EVA fields are not rendered at all. The EVA related view does not have any publish filter nor any permission that prevents unpublished content to be rendered. All modules are updated to latest stable version. Any idea?


texts: How can I route automated emails through an email function in my module?

texts:
I was unable to get HTML mail to use a template properly, so I have a mymodule_mail function that sends emails when a response is required from the user

function billiondollar_mail($key, &$message, $params) {
global $base_url;

$message['headers'] = array(
    'MIME-Version' => '1.0',
    'Return-Path' => 'xx@xx.com',
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
    'From' => 'XXXX <xx@xx.com>',
    'Content-Transfer-Encoding' => '8Bit',
    'X-Mailer' => 'Drupal'
);

I have a switch case on $key that loads in html header and footer plus the email body.

I'm wondering if there's some way I can make the system emails (some sent via trigger/actions and the registration confirmation ones) use that same system. Right now they are in plain text, which is incongruous with the rest of the system.

If I can get them using that hook function I will need to know what $key value it would have and how to insert the message content.. presumably one of the $params


texts: How to prevent drupal 7 from saving a node

texts:
I have a dummy form that will act as a main switchboard for all my content types. For example:

My starting point in the form fill up process starts with the 'Enter basic categories' node type where user specifies the categories in a taxonomy hierarchy:

Classifieds
  -Autos
    -Aston Martin
  -Computers
   -Desktop
   -Laptop
  -Jobs
A user then selects any of the terms and the page now redirects to the appropriate content type form, e.g. computers_node_form

The thing is that Drupal saves this Enter Basic Categories Node Form data that I no longer needed.

Is there a way to cancel or prevent Drupal 7 to save the first content type before the redirect? Any suggestions?


texts: Passing variable data into scss from twig

texts:
Is it possible to pass variable data from twig into css, like is done in this non drupal related question. The accepted answer suggests it's possible.
My Drupal project uses data from image fields to set the background image of page content.
Currently, I am achieving the desired effect by doing the following in my twig template:

But, rather than set the image data as attributes, I am looking for a cleaner solution in which I can set the background in css with the url data passed in as a variable.
The linked question above suggests it's possible but when I try I get the following results in my markup inspector:

That's the result of amending my code above to the following:

I'd appreciate any insights.


texts: Send email notification for the new created survey using webform

texts: I'm looking for a way to send email notification to all my users once my scheduled survey is already open. Upon checking the Webform module, all I can see about email notification is when a user submitted a response to the surey.


texts:
I've been working on a custom rest module for Drupal. I wrote the following Resource class.

    <?php

namespace Drupal\aker_platform\Plugin\rest\resource;

/**
 * Provides a License GET Resource
 *
 * @RestResource(
 *   id = "license_resource",
 *   label = @Translation("License Resource"),
 *   uri_paths = {
 *     "canonical" = "/aker/api/license/{id}",
 *     "https://www.drupal.org/link-relations/create" = "/aker/api/license",
 *
 *   }
 * )
 */

class LicenseResource extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get($id) {
    // Bla bla code for GET requests
  }

  /**
   * Responds to entity POST requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function post($data) {
     // bla bla for post requests.
  }

}

The get route works well, i enabled the routes using Rest UI:

My custom skeleton structure:

src
 -Entity
   LicenseEntity.php
 -Plugin
   -rest
    -resource
     LicenseResource.php
aker_platform.info.yml

To test the endpoint, i'm using curl:

curl --header "Content-Type: application/json" \
  --request POST \
  --data-binary '{"username":"xyz","password":"xyz"}' \
  mydomain/aker/api/license?_format=json

Also the endpoint was added to Anonymous guests to perform the requests without authentication.


texts: Why isn't ['field_name'][0]['#markup'] work for getting taxonomy of this node?

texts:
I have two content types: Case and News.
In node--case.tpl.php, I'm using echo $content['field_case_category'][0]['#markup']; in order to print the taxonomy term for the page and that works fine. In node--news.tpl.php, I can't use echo $content['field_news_category'][0]['#markup'];; in fact, #markup is not even present in this array at all.

Why doesn't this method work in the second case? What can I do to solve it?
Is there a better/right way to print taxonomy terms in nodes?

The error I get is the following:

  Notice: Undefined index: #markup in include()


texts: Allow user to choose role immediately after registration

texts:
I have 2 roles (driver, owner) with very different permissions on my site. I want to allow Facebook Connect during registration, so I am resigned to a 2-step registration process:

Register as a basic user via Facebook Connect or standard Drupal registration.
Basic user selects the appropriate role.

I will auto-assign the role "basic" upon registration and present a block to all users of the basic role which asks them to select Driver or Owner as their account type. Upon clicking the appropriate link, their user account will be updated with the new role. I can use Rules to remove the "basic" role whenever an account has been saved with one of the other roles.

How can I assign a role using a link displayed in a block?

Thank you.


texts: Why is webform submit handler not working in form alter?

texts:
webform submit handler not calling in form alter. I have tried solutions like
   use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_form_submit';
  }
}

function MODULENAME_form_submit($form, FormStateInterface $form_state) {
  print_r($form_state);
}

But this one is not working. Any help?


texts:
I have a drupal 7 site, competely upd to date. Installed Leaflet en put the leaflet libarie (unzipped) (https://leafletjs.com/) (1.5.1) in the sites/all/libraries/leaflet.

However, in the statusreport keeps the warning that the version is not detected. I tried and I tried, nothing helps...
any idea?

This is the warning:

Fout
Leaflet not detected
De versie van de bibiotheek Leaflet JavaScript Library werd niet gedetecteerd.

Translated (last line): The version of the library 'Leaflet JavaScript Library' was not detected.

Can anybody help?


texts:
Is there a way to make Drupal post to facebook?

I want the user to be able to create an article, and when user does that, it automatically posts information of the new article to a Facebook account. Is this possible?


texts:
This is the scenario if the user logs in from the home page <front> he should be redirected to dashboard. If he logs in from some other page he should be redirected to the same page. I think that Login Destination and Login Taboggon can do this, but I am not sure how to use them both.

By the way I am using D7.


texts: A quick way to load images from a list of urls

texts:
With media file selector widget it's possible to add images right from the web, without prior downloading them to the desktop.

But it quickly get's rather tedious if you have a list of image urls.

For adding multiple images from local drive there is a wonderful plupload module. But what's about convenient loading of remote files?


texts:
We have several sites running with Drupal.
On my local machine I run the test versions of each site in the Docker container to add new features or test new ones.
When switching between pages I do the following.
Shut down the container of page-A.
Change to the directory of page-B, start the container.
Then execute the following commands in the terminal in the container:
composer clearcache
composer install
drush sql-drop --yes;
drush sqlc < page-B_init.sql
drush updb
drush cim

When running drush cim, the following error message appears:
 [error]  Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization.
Entity type mismatch on rename.  not equal to configurable_language for existing configuration system.site and staged configuration language.entity.en.
Rename operation for simple configuration. Existing configuration system.site and staged configuration language.entity.en. in Drupal\Core\Config\ConfigImporter->validate() (line 755 of /var/www/html/docroot/core/lib/Drupal/Core/Config/ConfigImporter.php).

In ConfigImportCommands.php line 261:

  The import failed due to the following reasons:
  Entity type mismatch on rename.  not equal to configurable_language for existing configuration system.site and staged configuration language.entity.en.
  Rename operation for simple configuration. Existing configuration system.site and staged configuration language.entity.en.

I suspect the problem is with the UUID, which I have in the files:
environments/_default/config/sync/system.site.yml
environments/_default/config/sync/language.entity.en.yml

adapted.
But I don't know any further.
Does anyone have an idea where the error lies?
Use Drupal 8.9.13


texts:
I'm certainly a noob, so sorry for this if it's very basic.

I had an installation of D6 and the following code was working perfectly. But when I upgraded to D7, the page was posted, but the body wasn't being uploaded. I see that the location of the body has changed in the MySQL structure, but how do I address it in the code? Here's what was working in D6:

    $node->name = rand();
$node->title = $content->title;
$node->created = time();
$node->status = 1; //published
$node->promote = 0;
$node->sticky = 0;
$node->body = $content->data;
$node->type = 'page';
//$node->path = $content->path;
$node->revision = 'true';
node_save($node);

Interestingly, when I try to specify the path, the node_save returns an error, but when I specify body, it fires, but the body never shows up.

Can anyone help? I've spent a lot of time on this... much appreciated.


texts: Define node array id as parameter in routing

texts:
Is that possible to send somehow an array of nids and automatically convert it into and array of nodes? Something like:

custom.custom_nodes:
  path: '/custom/{nodes}'
  defaults:
    _form: '\Drupal\custom\Form\CustomForm'
    _title_callback: '\Drupal\custom\Form\CustomForm::titleCallback'
    nodes: []
  requirements:
    _access: 'TRUE'

Then I call this: /custom/1+2+3

And I will get at the backend an array of loaded nodes, which id's is 1, 2, 3.

If yes, how do I need to separate the nids from eachother? (And what else do I need to do?) Are there any best practice right now for this? What do I need if I need just an array of ids?


texts: Mysterious "Page not found" on every page load for authenticated users

texts:
I recently migrated my site to a new server, and restructured the urls, etc... so naturally there are quite a few 404's out there from other sites linking to old content. So far, so normal.

But among the page not founds, I'm getting something really bizarre: as far as I can tell, every single page load of the site by authenticated users is generating one particular "page not found" error for a file at location sites/default/files/stripes54-navywhite.jpg.

Every page load for every authenticated user.

Now this file does not exist. Nor are there any links on the site to it (the file name is familiar: we may have had a file at that location at some point in the past, on the old site).

I have searched page source, I have searched through the contents of all my site files, I have searched my complete db using phpmyadmin. There is no reference to this file anywhere, as far as I can tell.

So what could possibly be causing this? Where is this file mysteriously being referenced? Watchdog is giving me no help here.

My only clue at the moment is that this page not found seems to ONLY be triggered by authenticated users: not seeing any anonymous users triggering it.

Does anyone have any earthly idea what might be going on here? A big thanks to anyone who can help!

I'm even getting this error generated by admin pages, which use a separate admin theme. For example, when browsing my database log.

There is one entry in the file_managed table where origname is stripes54-navywhite.jpg. Unfortunately, this doesn't really shed much light on the problem.


texts: Since updating to Drupal 7.31 the WYSIWYG TinyMCE editor only works for my Administrator Role.  For my Manager Role it now only works with Comments and Blocks but not for Articles and Blogs.


texts: Adding more variables to menu for use in menu.html.twig

texts:
I'm attempting to give menus more variables to work with besides the default menu_name,items, and attributes. This is because making a variable in the preprocess menu hook does not allow it to be accessible in the menu.html.twig template.

My ultimate goal is to be able to add menu items that contain the user id in the path.

I believe I need to add the var to menu by using hook_theme_registry_alter and follow the format of https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/drupal_common_theme/8.2.x

So I attempted to add a variable to menu in my .theme file like so

function mytheme_theme_registry_alter(&$theme_registry){
    $theme_registry['menu']['variables']['test_var'] = 'testing theme registry alter';
}

But when I do so nothing appears when I alter menu.html.twig like so

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

        {% else %}

            {% endif %}
            {% for item in items %}
                {% if item.below %}

                {% else %}

                {% endif %}
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}

            {% endfor %}

{{ test_var }}

        {% endif %}
        {% endmacro %}

How would I add more menu variables for use in menu.html.twig ?

UPDATE: I also tried {{menus.test_var}} but that just broke the page

UPDATE 2: Using {{ kint() }} the test_var did not appear anywhere


texts:
I was using

  "repositories": {
   "drupal": {
       "type": "composer",
       "url": "https://packagist.drupal-composer.org/"
   }
  },

in my composer.json file, but now it started saying that it can't load it and it is deprecated so go to https://www.drupal.org/node/2822344 instead. However, the info on there suggests changing it to point to https://packages.drupal.org/7 but this also doesn't seem to exist.

Can anyone shed some light?


texts: Drush install on RedHat 6 seems to do nothing

texts:
I'm trying to get drush installed on a RHEL6 server. I've done the install via pear and also by unpacking the tar ball to /usr/local/share. Both methods result in the same result: typing "drush" from any location does nothing. To be more specific it hangs without any errors that I can see.

It doesn't give any error about not finding it in the path, it just hangs.

I have had it working on other RHEL6 machines, but I haven't been able to pin down any differences between the installs to give me an idea what's wrong with this one.


texts:
What is the best way to add taxonomy terms to each field value (uploaded with plupload or multiupload at once) of a imagefield (should look like http://www.binaerschmiede.at/test/imagefield-tags.jpg)?

Of course I want to access this terms in views afterwards for creating media overviews.

Is there already a extension/module I've missed so far while searching because I suppose I'm not the first one with that kind of request, am I?

Example:

I create a content where I upload 3 pictures to a multiple plupload image field. Entering title, alt text and the tag the first 2 images with "Nature, Animals", the 3rd on with "Nature, Landscape".
I create another content with 2 images tagged as with "Zoo, Animals".
In a View I want all to get all images tagged with "Animals", on another view all images tagged with "Nature", ... and so on.

Thanks.


texts: How to set multiple entity references as default values using the hook_form_alter()

texts:
I have a node which when renders an adds an entityform to the page.

The node has a entity ref field which references multiple other nodes. (eg: Products A, Product B, Product C, etc)

What I need is a rating from each user for each product who views the node.

Eg :
Node 1 | User 1
Product A : rating1
Product B : rating2
Product C : rating3

Node 1 | User 2
Product A : rating4
Product B : rating5
Product C : rating6

How could i establish such a thing?


texts: I can't to expose the option sort Post Date in a view in Drupal 7

texts:
I have created a view type content, with the follow features:

Format

Format: Unformatted list | Settings

Show: Content | Teaser

Fields

The selected style or row format does not utilize fields.

Filter criteria

Content: Type (= article)

Content: Published (Yes)

Sort criteria

Content: Post date (desc)

When I checked the option "Expose this sort to visitors, to allow them to change it " in Sort Criteria>Post Date and press Apply, the sort Expose doesn't show and when I am going again to Post Date I can see that the change was not stored, the "Expose this sort to visitors, to allow them to change it" appears unabled.

What's my error?

Thanks for your help.


texts: Where are admin/config/user-interface/archive setting stored

texts: Where are these settings stored at. On the disk? In a database table?


texts: db_select() which selects nodes which have a certain term

texts:
I feel like this should be a simple question and therefore have been answered before, but all of the other Stackexchange answers I find doesn't seem to directly answer the question (at least as far as I can understand).

$query = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('status', 1)
      ->condition('type', 'photo_gallery')
      ->orderBy('created', 'DESC')
      ->execute();

This is my db_select() to fetch a list of nodes.

My photo_gallery content type also has a term reference field named field_tags which references the tags taxonomy.

How do I select a list of nodes from the db and only get nodes which have a particular tag?


texts: Add cck field as scoring factor to drupal standard search

texts:
So, by default there are four scoring factors in drupal:

relevance of keyword
recency
number of comments
number of page views

I'd like to be able, to control relevance of specific cck-fields.
In my case, i've got a cck field (computed field), where all relevant search-data is getting summed up.

I'd like to be able to give this special field a higher relevancy to the search results than anything else.

Is there a possibility to do this?


texts: How do I embed a node creation form inside a view

texts:
I have a View with some fields and a couple of link items.

What I want to do is when I click on the link items, a node creation form associated with link should appear inside the view (the AJAX way).

The solution that I can think of is to embed the forms inside the view, but have no idea how to do that?

What is the best way to implement this?


texts: Custom theming: How to list multiple content types in the same page and use regions too

texts:
I created two content types: articles and press releases and I want to display those in the same page. I also am developing a custom theme.

So I created a view for that with the machine name press_release_list, created a template for it: views-view--press-release-list.html.twig and it works perfectly.

The problem is, I cannot make use of regions. I mean, I have content and side_menu regions and I want to add a twitter feed to the side menu. I add the block through "block layout" menu, it can be configured to be displayed on article and press release nodes however there is no option for the view I created...

I'm quite new to Drupal so what would be the best way to do this, is there a way to display the block on the view or is there a better option than creating a view?


texts: How do I export content from staging to production?

texts:
I'm looking for a way to export individual content items from a staging website to a production website. I've found the node export and content synchronization modules as possible solutions but I'm not feeling comfortable about using those modules on Drupal 9.
Anyone have any experience with this on Drupal 9? Any other modules I should be looking at?


texts: What are the functions of the callbacks in the commerce payment method info hook?

texts:
Can someone explain me the differences, maybe with some examples, between the callbacks in the hook_commerce_payment_method_info()?

The callbacks are these: settings_form, submit_form, submit_form_validate, submit_form_submit, redirect_form, redirect_form_validate, redirect_form_submit.

I'm trying to implement a payment module and I need to know how to use the callback of the above-mentioned hook.

Thanks


texts: Vertical columns using Views Responsive Grid module

texts:
I have created a view that groups items by type.  The output is in responsive columns, accomplished using the Views Responsive Grid module.  However, the items should be listed vertically, but they are being listed horizontally regardless of what I set the Alignment to in Style Options.

Has anybody found a fix for this?


texts:
in hook_file_download there is just a parameter named uri. How can I get nid of the node that contains the file in uri?

For exmpale I have a file field in my content type.I create a node and add some files to file field. Now when this file is going to be downloaded, in hook_file_download I want to get nid of the file.How?


texts: How to access raw data in twig template using views table format

texts:
I use a table format view to display a list of articles article-list using draggable views to allow editors to order the list. I customize the content of rows depending on a boolean field is_header and a formatted text field title_override. I have sub-themed views-view-table--article-list.html.twig to accomplish this. It works well enough.

In the template, I test the truth of is_header and the non-emptiness of title_override as follows:

    {% if row.columns.field_is_header|render|striptags|trim %}

and

    {% if row.columns.field_title_override|render|striptags|trim %}

These tests yield the proper results, but they make the template very slow! Anything less than render|striptags|trim doesn't work.

QUESTION:

Is there a way to directly access the raw data values of these variables to avoid the render|striptags|trim overhead?

I've seen suggestions to use something like row._entity.field_is_header, but this way of using _entity seems to work only in templates for the HTML or Unformatted view styles. Seems like there should be an easy way to do this.

As a note, switching to using an HTML or Unformatted style doesn't seem possible because AFAIK draggable views can be set up only with the table format.

ANSWER:

Thanks to 4k4 for the answer to this question (see below). To apply his/her general answer to my specific question, here is a snippet of the twig script I ended up with:

{% for key, row in rows %}
  {% if view.field.field_is_header.value(view.result[key]) %}
    <conditional stuff>
  {% endif %}
  {% if view.field.field_title_override.value(view.result[key]) %}
    <stuff when the override is non-empty>
  {% else %}
    <stuff when the override is empty>
  {% endif %}
{% endfor %}

Note that rows is an array normally passed to the views-view-table.html.twig template, as documented in the original template's header comments. Note also that the availability of the view array is NOT documented in the original template's header comments (not that it would have saved me without 4k4's help).


texts: How to integrate Lockr encryption key with Ubercart credit card payments

texts:
We migrated a client to Pantheon hosting a couple months ago. The site’s ubercart payments worked consistently on the old hosting platform, but  have only worked sporadically on pantheon and I’m trying to resolve the issue. It seems that the only payments that go through are ones made immediately after Drupal’s caches have been flushed.

I believe the problem is due to the credit card encryption: while I can set a directory in ubercart’s “Encryption key directory” field and I can see that the key does get generated, most payment transactions fail.

Ubercart wants you to store this key outside your doc root or in sites/default/files/private. I think this probably works perfectly on a normal hosting platform, but on Pantheon, the structure is different with sites/default/files/private not within the site's doc root.

I have read both of these pantheon guides: https://pantheon.io/docs/guides/lockr/ and https://pantheon.io/docs/private-paths/. Based on this info, I have installed the Drupal Key, Encrypt and Lockr modules and have enabled them.

In the Key module admin UI, I was able to signup for a Lockr account and add an encryption key of type Lockr encryption.

But now I don’t know how to make ubercart use this Lockr key. In Ubercart’s payment settings, under “Encryption key directory” it expects/requires a path to the key: what would this be for a Lockr key?

In the README for the Key module under the section "Using Keys" it seems to indicate I will have to write a custom module to make the Lockr key appear as a selectable option in the ubercart key directory settings. But I worry this may be beyond my abilities or consume vast amounts of time to figure out.

Is there an easy way to make ubercart use a Lockr key? Or has anyone written a custom module for this they'd be willing to share?


texts: How to get vote results from node reference through views?

texts:
I have two content types:
1. Restaurant page
2. Write a review page
The write a review page has node reference url widget field and also the fivestar rating field. The image attached below will explain more:

I have created a view page, where I want to get vote average results for each restaurant (also if possible than on each individual restaurants page too). I basically want average result of ratings given to each restaurant page by the node reference content type which is write a review page.
Below are two images explaining my view:

And the preview:

Now I am really not sure what I am doing wrong here, I changed aggregation settings for all randomly to average to count to all the possible scenarios but nothing seems to work. The votingapi_vote table is also empty, I know that fivestar doesnt necessarily use those tables to store, but then how could I display the stars or even the average of all the ratings that restaurant has got?

------------ update 1 -------------------------

Here is the relationship content type which I am getting:


texts: How to load module include files in .test file?

texts:
I'm trying to update the Drupal 7 version of the password_policy.test file that is included with the Password Policy module. When I run the tests, I'm getting "Fatal error: Call to undefined function password_policy_constraint_uppercase_validate()".

The function in question is in an include file in the constraints subdirectory, located inside the module's directory. I've tried adding to the test's setUp() function, along the lines of:

drupal_load('module', 'password_policy');
module_load_include('inc', 'password_policy', 'constraint_uppercase');

I've also tried adding the module_load_include line inside the individual test method generating the error. However, none of my attempts so far appear to be working and the error still persists.

How should I go about loading the ./constraints/constraint_uppercase.inc and other include files, so that the necessary functions are loaded prior to the tests being run?


texts:
I am trying to retrieve the product IDs. I can find a product SKU by looking on the product page and using commerce_product_load_by_sku() to load it.

How can I find the actual ID? I would like to use it in commerce_cart_product_add_by_id().


texts: How to render taxonomy in page template?

texts:
I'm trying to show all taxonomy terms in a custom template (page--project.tpl.php) that overrides page.tpl.php, but I can't pull it off.

I'd like to use the default rendering that I get when I see with
render($page['content']):

It seems like I should be able to use render($node->field_project_tags), but I get a bunch of drupal errors on the rendered template page:

Warning: Invalid argument supplied for foreach() in element_children() (line 6590 of /Users/username/sites/d7/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line 6047 of /Users/username/sites/d7/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line 6057 of /Users/username/sites/d7/includes/common.inc).
...

What's the cleanest, simplest way to render these taxonomy terms (as links) in a page template?


texts:
I'd like to add a custom attribute into the title element whenever a particular content type is displayed, whether as an individual node or through a view (specifically when displaying 'full content').  How do I do this?

I'm using Drupal 7.


texts: How to get Breadcrumb Trail from a book page?

texts: if given that we know the nid of a page in a book, how to construct some breadcrumbs or hierarchy from top of the book to the current page (nid)?


texts:
Why is there a 'Security Filters' section within the CKEditor configuration settings?

My understanding is that this is all set within the normal Drupal input formats section (admin/settings/filters). Do the CKEditor input configs replace this when the editor is present in a field?

:-/


texts: Facets hierarchical taxonomy terms not working

texts:
I use the Facet module version 8.x-1.x-dev. I have a list of taxonomy terms with parents and childs.

The taxonomy term facet is an Entity reference field. I can't get the hierarchical structure working in the frontend.


texts: when I create a simple basic page like About Us and I click Save Preview I get the errror ”The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "" (without the quotes) to fine-tune where your post gets split.” How can I get rid of this?


texts: Show 4 input file fields on my node add image page

texts: I have a content type with an image field; the user can insert a maximum of 4 images. I need both the node add and edit form to show 4 input file elements, not only 1.


texts: Drush 8.0.3 is unable to update D7 modules

texts:
I have Drush installed via Homebrew on my Mac. I am currently unable to execute "drush up" in a Drupal web site. When I attempt, I get the error:

Destination directory [...] already exists.

Is this normal? Do I need to use a different version? Do I need to stop using Homebrew?


texts: How to programatically add content-type as a row class in views

texts:
I have a view that is displaying Full Content of several different content types, using the Masonry Views view module. I would like to add a class to each node display that is equal to the content type.

The template provided with the module is:

<?php foreach ($rows as $id => $row): ?>

  <div class="masonry-item<?php if ($classes_array[$id]) print ' ' . $classes_array[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

I can't figure out how to add the content type as a class, as I can't find that variable in the $row. How can i add the content type as a class to each item?


texts: How to configure wysiwyg_tools_plus module?

texts:
Has anyone used this module (wysiwyg_tools_plus)?  It give ckeditor the ability to create tabs & accordion effects via a wysiwyg (sample video).  The docs on usage look good, but I'm having a hell of a time figuring out how to actually get the icons to show up in ckeditor.

I've done this:

installed ckeditor module & verified usage
installed/enabled wysiwyg_tools_plus
set ckeditor as the editor for my text formats
tried to edit profiles (/admin/config/content/wysiwyg/profile/full_html/edit), but haven't found a way to add the Tab or Accordion buttons

Any idea what I need to configure?


texts: Views/Block: Only display if node field has a value

texts:
I've created a Block in Views. I only want this Block to display if a boolean field on the node is ticked. The View itself should only display content that relates to the node. How can I do this?

When displaying content in Views that relates to a node, you can normally use "Context Filters ID: Node". This would allow a View to take over a node. But it only seems to work in the Page display of the View and not the Block display.

I now I can use modules such as Rules, Panels or Node Fields Block to achieve this. But those are quite big modules and I only want to use it for a small thing on my site, so I was hoping their might be some solutions that can be done without any extra modules.


texts: How to add multiple taxonomy term to a single node in drupal 7?

texts:
Using Taxonomy terms auto-complete wizard I can able to add one term to the a node. But I wanted to add multiple terms to a single node? Is it possible? If so, is there any modules or plugins or any configuration options in existing module?

In the above screen shot, I can able to add only one term. But I want to do in the way shown below.


texts:
My problem is not technical but structural.

The idea is that users can submit an ad (to sell a car for instance) with entityForm, or webform.

To define the car to sell, I want a predefined list to avoid misspelled words.

The first solution I tested was to use Taxonomy like that:

-Audi
--A1
--A3
--A4
-Seat
--Ibiza
--Leon

I used "Hierarchical Select" and then "Simple Hierarchical Select" and even "Term Reference Tree" but my problem is still the same.

When I want to use a view to display the EntityForm Submissions, it shows the car in one column like that:

Car

.Audi
..A1

.Audi
..A3

And I want it on 2 columns like that:

Brand | Model

Audi  | A1
Audi  | A3

Does taxonomy allow that and how?

Should I use a database table with another module?

Thanks for any help!


texts: Strange problem with autocomplete field in forms in Drupal 7

texts:
I have an autocomplete field, which has been working perfectly for 1-2 days. Suddenly, it stoped working. I re-wrote the code, cleared the cache, and it works again. After comparing code, it is exactly the same code. I cannot trace the error. The problem is that it does not give back any results and the Firebug error is:

  TypeError: matches is null if (typeof matches.status == 'undefined' || matches.status != 0) ...

I cannot understand why it suddenly stopped working.

I have traced back the problem to a warning by Drupal:

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '_search_idiomas_autocomplete/list/confirm/' not found or invalid function name in menu_execute_active_handler()

Still not sure where the problem is. The code is standard autocomplete field from official documentation examples.


texts: Drush archive-dump database dump failed on XAMPP

texts:
I want to import my local drupal site in another machine. This is what I ran from DOS from drupal root folder to get my site archive

drush archive-dump --destination=mysite.com.tar.gz

After few seconds it just stop after this message

Database dump failed.

I see the mysite.com.tar.gz file is created with my webroot fils. I don't think it created any db dump file which sounds obvious because of that error message.

These are mysql.ini settings (note the modified settings commented inline)

key_buffer = 16M
max_allowed_packet = 2M -- THIS WAS 1M
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error = "mysql_error.log"
[mysqldump]
quick
max_allowed_packet = 32M -- THIS WAS 16M

What do I need to do create archive without this error? I am open for other alternatives too (other than manually ftp and dumping db file)


texts: Is FIELD COLLECTION VIEWS module only for showing data in table format?

texts: I am using field collection module and in search of formatting it I came across field collection views module. But whatever tutorial I came across, in all it is display data in Table form only. Is there possibility that we can use field collection views module as Views module so we can have lots of option for formatting? Or Field collection views module is limited to show data to Table format only?


texts: I cannot update because of Ubercart and Google Analytics module error

texts:
I tried updating my Google Analytics module today, but when I went to the update.php page I got this error:

Unresolved dependency. Google Analytics (Version !=7.x-2.4 required)
Google Analytics for Ubercart requires this module and version.   Currently using Google Analytics version 2.4

I've tried everything to resolve this error. I found this page pretty easy, but none of the suggestions work. I installed Google Analytics 7.x-2.6, so I shouldn't be getting this error.

So far, I've tried:

Clearing my cache
Installing Google Analytics 7.x-2.3 and 7.x-2.x-dev
Downloading the latest version of Ubercart
Refreshing update.php and clearing browser's cache
Modifying ubercart module's uc_googleanalytics.info like the link above describes

I can't disable the Google Analytics module either because the checkbox is greyed out


texts: Resizing image from one field and save result in another field

texts: As mentioned on the comments on this question, on my node-editing-form there are fields for WIDTH, HEIGHT, and an IMAGE. I would like to resize the given image by the dimesions WIDTH and HEIGHT and to save the result in another image field. I hope someone could outline (or even concretise) how to build that module.


texts: How do I grab a list of all fields in a content type?

texts: How would I grab a list of all the fields in a content type? Currently, I'm using entity_metadata_wrapper() to grab each field individually, but I feel that there's probably a more efficient way to get all of the values for a given content type.


texts: Preprocess Menu Link Independent of menu.html.twig?

texts:
I am hoping there is a way to alter a menu link independent of menu.html.twig

Motivation is this example from Bootstrap theme menu.html.twig:

{% set link_title = item.title %}
{% set link_title %}{{ link_title }} {% endset %}

The Twig template is adding markup to the link $variables['text'] of hook_link_alter().

I'm altering the text of a menu link item but retaining any HTML it might have. I have the below which works:

function hook_link_alter(&$variables) {

  $linkText = $variables['text'];
  $cleanLinkText = rtrim(strip_tags($linkText));

  if ($cleanLinkText == 'string') {

    $linkMarkup = str_replace($cleanLinkText, '', $linkText);

    // c_Markup() returns a new TranslatableMarkup().
    // We have to pass back in the HTML.
    $markup = c_Markup($linkMarkup);

    $variables['text'] = $markup;

  }

}

Things like str_replace and trim are very powerful, but I would prefer I use the appropriate hook for the need.

Have worked with hook_preprocess_menu(&$variables, $hook) without better success.

Update: This also works and I am able to get the text without the markup. Yet it seems like a lot more work to cycle through all the entire menu tree.

function hook_preprocess_menu(&$variables, $hook) {

  foreach ($variables['items'] as &$key) {

    $title = rtrim(strip_tags($key['title']));

    if ($title == 'string') {

      $key['title'] = $markup;

    }

    foreach ($key['below'] as &$beKey) {

      if ($beTitle == 'string') {

        $beKey['title'] = $markup;

      }

    }

  }

}

I guess this answers my question but is there a more direct hook/method to use? Under $key['original_link'] I can see the protected Translatable Markup for the link title.


texts: Assessing admin when site is not hosted in the root of the domain

texts:
We set up a site with a url like www.mysite.com
the site is being served by a proxy to come up as

www.theirsite.com/mysite/

We set $base_url  to www.theirsite/mysite

This is working correctly to load all the assets on the page but does not work on the admin.

The admin login and all pages on the admin try to post to the root of www.theirsite.com
so for instance the /user page tries to post to
www.theirsite.com/user
this is obviously not working.

We tried clearing the cache on drupal to rebuild all urls as was recommended on many sites, but did not have any effect.

We are hosting our site via iis7 on windows.
The version of Drupal is 7.2

What can be done to fix the admin form urls?


texts: Add a custom submission handler to a form

texts:
How can I add a custom form submission handler?

I tried adding $form['#submit'][] = 'mymodule_form_submit'; or $form['actions']['submit']['#submit'][] = 'mymodule_form_submit'; to hook_form_alter().

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
      }
    }
  }
}

function mymodule_form_submit(array $form, FormStateInterface $form_state){
    //die("why won't this execute? :(");
    drupal_set_message("Why won't this message show?");
}

It seems drupal_set_message() is not called. I also tried rebuilding the cache, but the function is still not called.

I am using Drupal 8.2.3.


texts: How do I make the content of one user not accessible to other

texts: I have created separate dashboard for each student using login destination module. I am able to redirect the student to their profile page. There are some other pages (score card, attendence etc) which are different for each student. how do I make the details of one student not accessible for other?


texts: Corrent syntax for an ajax callback inline in Drupal 7

texts:
I have a custom block on my pages that displays total a total hit count amongst other stats for 'wiki' node types. For logged in users, I am able to increment this count each time straight in PHP but for anonymous users there is the page cache.

To get around this, I added a js ajax segment inline. The ajax calls the server for the latest data, which once received updates on the client side.

This is working successfully but I have 2 questions:

Is this a good solution to be doing what I want?
I've only just started using AJAX in D7. I couldn't figure it out, but could I do what i'm trying to do with the new Ajax framework?

The code:

/**
 * Implements hook_menu().
 */
function wiki_menu() {
    $items = array();

  $items['wiki/ajax/stats/%'] = array(
    'page callback' => 'wiki_ajax_stats',
    'page arguments' => array(3),
    'access callback' => '_wiki_ajax_stats_access',
    'access arguments' => array(3),
    'file' => 'wiki.pages.inc',
    'type' => MENU_CALLBACK,
  );

    return $items;
}

/**
 * Implements hook_block_view().
 */
function wiki_block_view($delta = '') {
    // Our blocks are set to only be visible on content types wiki and wiki_subpage
    $node = menu_get_object();

    $block = array();

  switch ($delta) {
    case 'stats':
            $block['subject'] = t('Statistics');

      if (!user_is_logged_in()) {
        // Path for ajax callback
        $url = url('wiki/ajax/stats/' . $node->book['bid']);

                // Add ajax callback inline for anonymous users
        drupal_add_js('jQuery(document).ready(function() {
          jQuery.ajax({
            url: "' . $url .  '",
            dataType: "json",
            cache: false,
            success: function(data){
             jQuery("#block-wiki-stats td.today-value").text(data.today);
             jQuery("#block-wiki-stats td.total-value").text(data.total);
            }
          });
        });', array('type' => 'inline', 'scope' => 'footer'));
      }
      else {
                _wiki_stats_increment($node->book['bid']);
      }

      $block['content'] = _wiki_block_stats($node);
      break;
  }
  return $block;
}

/**
 * // Update the number of views for the node.
 */
function _wiki_stats_increment($nid) {
    db_update('wiki_stats')
        ->expression('today', 'today + :today', array(':today' => 1))
        ->expression('total', 'total + :total', array(':total' => 1))
        ->condition('nid', $nid)
        ->execute();
}

/**
 * Callback for stats block
 *
 * @return
 *  Themed output for the activity block
 */
function _wiki_block_stats($node) {
    $stats = db_select('wiki_stats')
      ->fields('wiki_stats', array('today', 'yesterday', 'total'))
        ->condition('nid', $node->book['bid'])
        ->execute()
        ->fetchAssoc();

    $header = array(
        array('data' => t('Activity'), 'colspan' => 2),
    );

    $rows = array(
        array(t('Today'), array('data' => $stats['today'], 'class' => 'today-value')),
        array(t('Yesterday'), $stats['yesterday']),
        array(t('All Time'), array('data' => $stats['total'], 'class' => 'total-value')),
    );

  return theme('table', array('header' => $header, 'rows' => $rows));
}

/**
 * Stats update needs to run in an ajax callback to bypass page caching
 */
function wiki_ajax_stats($bid) {
  _wiki_stats_increment($bid);

    $stats = db_select('wiki_stats')
      ->fields('wiki_stats', array('today', 'total'))
        ->condition('nid', $bid)
        ->execute()
        ->fetchAssoc();

    drupal_json_output($stats);
}


texts: Reset password via Services by email, and not by uid

texts:
I'm trying to POST an email address to the password_reset Services endpoint so that it generates and sends a password reset email for a user. When I post the uid to the endpoint, it does this successfully. That said, I want to post the user's email to the endpoint (e.g. they type in their email to retrieve their password recovery email). How can I change the below in order to allow this? I tried changing user_load($uid) to user_load_by_mail($uid), but this didn't work.

Endpoint format:

  mydomain.com/myendpoint/user/emailhere@go.com/password_reset_email

user_resource.inc

  $definition = array(
  'user' => array(
  'operations' => array(
  'actions' => array(
    'help' => 'Send forgot password email',
    'callback' => '_user_resource_password_reset_email',
    'access callback' => 'services_access_menu',
    'args' => array(
      array(
        'name' => 'email',
        'optional' => FALSE,
          'source' => array('data' => 'email'),
        'type' => 'string',
        'description' => 'The email address of the user whose password should be reset.',
      ),
      ),
    ),
    ),
    ),
  ),

       function _user_resource_password_reset_email($data) {
  global $language;

  $mail = _services_arg_value($data, 'data');
  $account = user_load_by_mail($mail);

  if (empty($account)) {
    return services_error(t('There is no user with email @email.', array('@email' => $mail)), 404);
  }

  // Mail one time login URL and instructions using current language.
  $mail = _user_mail_notify('password_reset_email', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
  else {
    watchdog('user', 'There was an error re-sending password reset instructions mailed to %name at %email', array('%name' => $account->name, '%email' => $account->mail));
}

  $result = "success";
  return $result;
}

Obj-C

ViewController.m

- (IBAction)sendButton:(id)sender {

[DIOSUser userSendPasswordRecoveryEmailWithEmailAddress:self.forgotField.text
                                                            success:^(AFHTTPRequestOperation *operation, id responseObject) {

                                                                NSLog(@"Password being sent!");

                                                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                                                message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                                                delegate:self
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil];
    [alert show];

      }failure:^( AFHTTPRequestOperation *operation , NSError *error ){

      if(!error){

     }
      }];

        }

DIOSUser.m

 + (void)userSendPasswordRecoveryEmailWithEmailAddress: (NSString*)email
                                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject)) success
                                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

   NSString *path = [NSString stringWithFormat:@"user/%@/request_new_password", email];

    [[DIOSSession sharedSession] sendRequestWithPath:path method:@"POST" params:nil success:success failure:failure];
}


texts:
I get an error at Reports menu as

and then when I click on "database update script", I see

I then click on "Apply Pending Updates", but i get the following error:

How can I fix it? What should I do about it?