texts: Render a custom form in a custom template

texts:
For my site, I have to create a custom form in a custom template. It is not in a custom block, but in a custom tpl-file. I have searched the internet for a solution, but or the form is not shown or the fields are shown, but not in a < form > tag. This way, the submit-button does not work. When I render the fields in a self-written form-tag, the validate function and submit-function don't work.

Can someone help me?

TPL-File

$form = _odisee_forms($form, $dag, $datum, $uur, $campussen);
$form['infodag'] = form_process_checkboxes($form['infodag']);
$formulier = drupal_get_form('infodagen-block-form');
print '<form id="'.$formulier['#id'].'" accept-charset="UTF-8" method="'.$formulier['#method'].'" action="'.$formulier['#action'].'">';
print drupal_render_children($form);
//print render($form);
print render($formulier['form_id']);
print render($formulier['form_build_id']);
print render($formulier['form_token']);
print '</form>';

forms.inc

function _odisee_forms($type, $dag, $datum, $uur, $campussen) {
  $form = array();
  foreach ($campussen as $key => $campus) {
  $infomoment[] = t($dag[$key])." ".$datum[$key]. " @ " .$campus. " om ".$uur[$key];
  }
  $form['#id'] = 'infodagen-block-form';
  $form['infodag'] = array(
    '#type' => 'checkboxes',
    '#options' => $infomoment,
    '#required' => TRUE,
  );
  $form['voornaam'] = array(
    '#type'  => 'textfield',
    '#title' => t(''),
    '#size'  => 15,
    '#attributes' => array(
      'placeholder' => array('Voornaam'),
      'class' => array('breed')
    ),
    '#required' => TRUE,
  );
  $form['naam'] = array(
    '#type'  => 'textfield',
    '#title' => t(''),
    '#size'  => 15,
    '#attributes' => array(
      'placeholder' => array('Naam'),
      'class' => array('breed')
    ),
    '#required' => TRUE,
  );
  $form['emailadres'] = array(
    '#type' => 'textfield',
    '#title' => t(''),
    '#size' => 20,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#attributes' => array(
      'placeholder' => array('E-mailadres'),
      'class' => array('breed')
    ),
  );
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => t('Schrijf in!'),
    '#attributes' => array('class' => array('button')),
    '#submit' => array('_odisee_form_submit'),
    '#validate' => array('_odisee_form_validate'),
  );
  return $form;
}

function _odisee_forms_validate($form_id, &$form, &$form_state) {
  dpm($form_state, "state");
  dpm($form);
}

function _odisee_forms_submit($form, &$form_state) {
}


texts: Can't use file field in custom form - gives AJAX errors

texts:
I'm building my own form for editing certain fields on a node type, and I'm using field_attach_form() to add the fields from that node type to my form.

Use field_attach_form() to get the fields added to the $form array, and then I hide the ones I don't need by setting them to '#access' => FALSE. For all the textual fields, selects, etc., there's no problem. But when I use a file field (for image uploads), and someone selects a file and clicks 'Upload' on that file field, I get the following two errors:

Notice: Undefined index: field_picture in file_ajax_upload() (line 268 of /path/to/drupal/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 277 of /path/to/drupal/modules/file/file.module).

I noticed over on drupal.org, merlinofchaos mentioned that a user could use form_load_include() to include an include that needs to be loaded with the particular form (see: http://drupal.org/node/1161430#comment-4540578), but that was more because that guy additionally had something else he was loading, I think.

The form is built in mymodule.pages.inc, and is called through a menu callback at a path like /admin/config/mymodule/edit-form. What am I missing?


texts: Change page title of a module generated page

texts:
I'm using the Tagclouds module to generate a list of items grouped by taxonomy. The URL looks like this:

http://example.com/tagclouds/list/2

This works fine. However the automatic generated title of this page is 'Labels'. Any ideas how I can substitute 'Labels' by something else?


texts:
I want create a related content block by searching in node title,for doing this i created a views and add a views search filter,my problem is i dont know how auto set node title as search value.
there is any token for filter value ? like [node:title] when user visit a node it put node,title in search value.


texts:
So I have a requirement that I'm getting close to stumped on how to complete in Drupal 8.

I'm going to attempt to simplify the requirements. I have two roles. They are essentially mutually exclusive. Let's call them "Internal" and "Client".

The request is to have Clients logged in for an indefinite period of time... let's call it years. Internal users need to be logged in for a short period of time, say 1 day, or even just the session.
(Note: I didn't make these requirements, just coding them... haha)

My understanding of the Drupal login is that there are really two things controlling this... there is the cookie lifetime of a user, and the session lifetime (on the server). If I set the cookie lifetime to 1 week, but the session lifetime is 1 day, the user will essentially be logged out after 1 day, b/c their cookie will match a session that doesn't exist after a day... is that right?

So, I think I have to start with the upper limit. If I want my user to be logged in for 1 year, I need my server session to be 1 year. One of my questions is: what are the risks/downsides/etc to setting my server session to 1 year? Let's say my server gets 50k visits a month. What if it's not 1 year, and I want it at 2 years? I can't seem to find a definitive guide to what the upper limit of server session should be? It seems like there's a lot of factors that could clear out that session as well...

Ok, so the above is one question... assuming I can set the server session, how can I have the cookie lifetime visit based on user role? I'm getting to the point where it seems like it just might not be possible to vary this setting, and I might have to do some kind of route subscriber and custom cookies and whanot to detect the internal users, and log them out when I see they've been logged in too long...

Any help would be much appreciated...


texts:
Is it possible to generate fields which are "grouped" together when marked as Unlimited? For example, a select field with label "What time do you wake up?" lets the user select the day of the week (Mon-Sun) then beside it an empty textfield to type in the time they get up. These 2 fields are "grouped" together. Then if they want to add another day of the week (Unlimited), the new field generates a dropdown menu and a textfield together all over again.

NOTE: No CCK please. I'm using Drupal 7 and it's already in the core.


texts:
I would like to set a custom message for my search using the core Drupal search module. Right now it says:

  Your search yielded no results Check if your spelling is
  correct. Remove quotes around phrases to search for each word
  individually. bike shed will often show more results than "bike
  shed". Consider loosening your query with OR. bike OR shed will
  often show more results than bike shed.


texts:
entity_get_controller() is giving me an error when I try to use a class. This class is defined in another file called ingredient.controller.inc

  Fatal error:  Class name must be a valid object or a string

The following code doesn't work:

 function ingredient_add() {
   $ingredient = entity_get_controller('ingredient')->create();
   return drupal_get_form('ingredient_add_form',$ingredient);
 }

The following one works;

function ingredient_add() {
  $ingredient = (object) array('iid' => '','name' => '',);
  return drupal_get_form('ingredient_add_form',$ingredient);
}

The class code is the following one:

class IngredientController extends DrupalDefaultEntityController {

    public function create() {
      return (object) array(
        'iid' => '',
        'name' => '',
      );
    }
}

function nutrition_entity_info() {
  $return['ingredient'] = array (
    'label' => t('Ingredient'),
    'controller class' => 'IngredientController',
    'base table' => 'ingredient',
    'uri callback' => 'ingredient_uri',
    'fieldable' => TRUE,
    'entity keys' => array (
      'id' => 'iid',
      'label' => 'name',
    ),
    'static cache' => TRUE,
    'view modes' => array (
      'full' => array (
        'label' => t('Full content'),
        'custom settings' => FALSE,
      ),
      'teaser' => array(
        'label' => t('Teaser'),
        'custom settings' => FALSE,
      ),
    ),
  );

  return $return;
}

Do you have any idea?

Should the implementation of hook_entity_info() be nutrition_entity_info() or ingredient_entity_info()?

Nutrition is the module name, ingredient the entity I am creating.

There was some kind of typo on the code, as it seems to work now.


texts: How to programmatically select a view display in a view based on some node data

texts:
I have a content type that includes a field to store how that node should be displayed (display_option). display_option has two values (1|2).

I have created a view with two displays. Both are pages. Both use the path /node/% and use the node id as a contextual filter.

Display 1 has an additional filter criteria for requiring that display_option = 1.

Display 2 has the same filter but with the criteria that display_option = 2.

I can supply a node id to each display preview and they both individually produce the content I am looking for.

I was hoping Drupal would simply select the correct display based on the filter criteria but it doesn't. It always uses the display that is first in the view.

So I was looking at adding a pre-process function of some kind to template.php to manually change the view display id based on the node data.

I see quite a few views pre-processing functions and I am not sure which to use or at what point in the page build and view build process.

Any help would be appreciated including another method for accomplishing this.


texts: is there any Function to extract all the view modes for specific node?

texts:
Is there any function which can give you all the types of view modes available for specific node?
Also is there any direct(UI) way to check it ?

Is going to edit->manage_display the only way to get the view modes ?


texts: Restrict search results to only documents user can see

texts:
In my application, I have a content type called resource. In the resource content type, I have an entity reference that defines which roles should be able to view that resource.

When somebody is logged in as a certain role and does a search, he is able to view documents that don't belong to his role. How can I hook to the search results and remove the ones he should not be able to see?

Thanks


texts: I have a Drupal 8 site and am encountering an issue. When I visit the site as an anonymous user and click a link on the menu, it adds /index.php to the url. Then if I navigate to that page and click another link in adds another index.php (i.e. example.com/index.php/index.php/link1/link2) and therefore the page will not load. This does not happen if I am logged into the site, has anyone encountered this before? I tried a fresh htaccess file and beyond that I am stumped. It is on a shared hosting plan. Any help is appreciated.


texts: modifying the ajax path of drupal ajax module forms submission

texts:
I'm using the Ajax module and following this documentation.

The thing is, my form is loaded via ahah, and when that happens whenever I submit the form, this modules make an ajax call to a messed up path (if it weren't loaded via ahah, the ajax that the form loads is fine)

Do any of you know how I can modify the path of this module's ajax call so that I can fix it accordingly?


texts:
I have a list field on Profile entity for civilities.
I want to get the value of this field in a specific value whatever is the current one.
Since the Profile isn't translatable I can't get a way to achieve that.
Any help is welcome


texts: js files inside custom directory deleted after cache clear

texts: I have 2 files with jquery code in custom directory www.mysite.com/files/js/...Every time I clear cache, the files are deleted from server. How is this possible? Anyone came across this issue?


texts:
I have a form  with 2 submit in it, one of them is a button to generate codes, everytimes I click on generate form_submited called up and a record insert in db, how can I prevent form_sumit in ajax triggering?

function rah_cc_generate_form($form,$form_state){
    $form=array();

    $form['gen']=array(
        '#type' => 'fieldset',
        '#name' =>t('generate gift card code'),
        '#collapsible' => TRUE,
        '#collapsed' => false,
//        '#weight' => 5,

    );
    $form['gen']['code']=array(
            '#type' => 'textfield',
            '#title' => t('gift code'),
            '#default_value' => '',
            '#prefix' => '
',
            '#suffix' => '
',
            '#size' => variable_get('rah_gc_code_size', 8),
            '#maxlength' => 20,
            //'#required' => TRUE,
    );
    $form['gen']['price']=array(
            '#type' => 'textfield',
            '#title' => t('price'),
            '#default_value' => 10000,
            '#size' => 10,
            '#maxlength' => 20,
            '#required' => TRUE,
    );
    $form['gen']['status'] = array(
  '#type' => 'checkbox',
  '#title' => t('status'),
    '#default_value' => 1,
);

    $form['gen']['random']=array(
     '#type' => 'submit',
    '#value' => t('generate'),
    '#description' => t("if you want generate random use this plz"),
    //'#weight' => 1,
    //'#submit' => array('rah_cc_generate_random'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'rah_cc_generate_ajax',
      'wrapper' => 'gc-code',
      'method' => 'replace',
      'effect' => 'fade',
      ),
   );

    $form['gen']['save']=array(
        '#type' => 'submit',
        '#value' =>t('save'),
         );
    ym($form);
    return $form;

}
function rah_cc_generate_ajax(&$form,$form_state){

    //return $form['gen']['code']['#default_value']=33;
     $form['gen']['code']['#value']=rah_cc_generate();
     //$form_state['values']['code']['und'][0]['value']=44;
     return $form['gen']['code'];

}

update
I use      'prevent'=> 'sumbit', but not get answer :(

 $form['gen']['random']=array(
     '#type' => 'submit',
    '#value' => t('generate'),
    '#description' => t("if you want generate random use this plz"),
    //'#weight' => 1,
    //'#submit' => array('rah_cc_generate_random'), // If no javascript action.
    '#ajax' => array(
      'callback' => 'rah_cc_generate_ajax',
      'wrapper' => 'gc-code',
      'method' => 'replace',
      'effect' => 'fade',
      'prevent'=> 'sumbit',
      ),
   );


texts: How to add edit link within add to cart form in ubercart drupal 7?

texts:
I need to add edit link within add to cart form in ubercart in Drupal 7.
I am using hook_form_uc_cart_view_form_alter() hook but not getting how to add edit link within this hook.


texts: Suggest a new template file for a page node view

texts:
I have a site which has two main views, a men's blog and a women's blog, both with their own content types, mens-blog-post and womens-blog-post. The problem I am facing is that they share the same page--node.tpl file (node page view, default file:page.tpl not node.tpl), but need to have different content (e.g. other relevant views in the sidebar region). I need to suggest two new template files called page--node--mens-blog-post.tpl.php and page--node—womens-blog-post.tpl.php based on content type.

Here is my attempt:

function force_preprocess_page(&$vars){
 if ($vars['content']->type == 'mens-blog-post') {
  array_unshift($vars['theme_hook_suggestions'], 'page__node__mens_blog_post');
 }
 if ($vars['content']->type == 'womens-blog-post'){
  array_unshift($vars['theme_hook_suggestions'], 'page__node__womens_blog_post');
 }
}

Can anyone help me clean this up and make it work? I am looking for any solution that works so I am open to other ideas.


texts: Printing a drupal 7 user field into a link

texts:
Ok so my goal here is to allow users to link there social media profiles onto their user pages. So i tried to print the field within an href statement so it would come out as a link.
For example if the value for the field link is http://www.google.com, then it should output the text link with a link to google when clicked.

But it doesnt, it instead outputs the value for the field_link and links it to

Heres what i attempted at:

<a href="<?php print render($user_profile['field_link']); ?>">Link

Any help is appreciated!

Edit:
Ok so this is what it outputs:

But i only want the web address
Please Help!!


texts: Adding a 'post to everyone' option in Drupal Commons

texts:
At present, Drupal Commons posts must be added to one or many groups or to trusted contacts. I would like to add a "public" post that everyone can see in their feed. This is simply a meta group that all members belong to given that my community is a smaller, private intranet.

So, I would like the post to have 3 options. 1) Post to a group(s), 2) post to trusted contacts, 3) post to the community.

Has anyone implemented this ?


texts: Node reference - show parent node when viewing child

texts:
I'm using References module. I have parent node where I can choose multiple child nodes for it. This parent has reference-field.
I have made views to list child nodes when viewing parent node.

Now I need to have views to show parent node when viewing child node.

This should be fairly easy to do(?), but I was not able to achieve it.
I tried with reverse reference relationship, but it does not show nothing on child page.

How to show parent node (in views) when viewing child node?


texts: Dynamically fill field when adding a new node

texts:
I have been trying to search for an answer to this but I am not entirely sure what to ask.  I am using drupal 7.  What I am trying to accomplish is being able to create a campaign, and then allowing users to order a product within that campaign.

So currently I have a content type of campaign and a content type of order.  I create a new campagin and then un-authenticated users should be able to create new Order nodes, but what I am not sure how to do, is link the orders to the campaign. So http://www.domain.com/campaign/name would have a form on it that generates a new order node.

It seems like I need to have entity reference in the order content type, but how to I populate that field because I don't want the user to select which campaign, it should be automatic.  Hopefully that makes sense, the only way I have thought to accomplish this would be to parse the uri and try to get the campaign name then lookup the campaign nid.  Seems kind of hackish though.  Thanks!


texts: Running an "is all of" filter on a field collection

texts:
I'm currently working with a field collection lets call it Certificates. Certificates contains the following fields... Certificate Type, Certificate Number, Expiration Date, Etc.
I have a content type called Applicant that contains the field collection Certificates. Ideally, I'm trying create a view that allows for a "is all of" filter for the various certificates. We are trying to filter candidates by multiple certificates at the same time. To complicate this further, I've been asked to do this in a single multiselect drop down using chosen. By adding the field-collection as a relationship, I am able to add a Chosen multiselect that works correctly with the "is one of" operator, but it won't work with the "is all of". I think that the reason for this is that it seems like the certificate type is overriding the actual field-collection in order to display the certificate. Looking for suggestions. Any help will be greatly appreciated!!!!


texts: Email filter in default admin users/people search form

texts:
I would like an additional filter (email-text input) in the drupal7 default admin users/people search form. Is there any module as I can't find one for drupal7?
I found that another way is the use of views but I want the default search form with additional input filter.


texts: How to print a field value from a referenced entity of a referenced entity in Drupal 8.4 and higher?

texts:
The question is split in two: printing values from one level reference. And printing value from second level reference. And how to do both in twig template and how to do both in admin UI?

First questions in detail: How can I print the value of a field from a referenced entity in the related node twig template or via admin UI in Drupal 8? For example: In a twig template file from a node type article referencing a node type event, where the event node type has a date field and the date from the referenced node type event its date field should be printed in the article node twig template? And what if I would like to make this theme indendent. How to solve this in field admin UI? Is this possible? Similar questions on DA have answers not working for me or outdated (< Drupal v8.4).

From there the second question arises: Is it possible to go one step further? What about a referenced node type called "userprofile" referenced to from a user account who is author of the node? What if I would like to print the image from this "userprofile" node type in the a node twig template or field admin UI of the node where the user is author of?

Questions close to this question but didn't worked for me or didn't helped me to find my answer:

Get referenced node fields in twig
Print author details in node
How can you render fields from an entity reference in node templates? [Drupal 8]
https://www.drupal.org/forum/general/general-discussion/2017-02-17/entity-reference-field-in-drupal-8
https://www.drupal.org/node/1327954


texts: Struggling with Feeds Importer to custom content type

texts:
I am struggling to get to grips with the Feeds Importer, getting it to create nodes of my custom content type.

I have created the Feed Importer :

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'feed_new_horizons';
$feeds_importer->config = array(
  'name' => 'New Horizons',
  'description' => 'NASA New Horizons News Feed',
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => FALSE,
      'use_pubsubhubbub' => FALSE,
      'designated_hub' => '',
      'request_timeout' => NULL,
      'auto_scheme' => 'http',
      'accept_invalid_cert' => FALSE,
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsSyndicationParser',
    'config' => array(),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '2592000',
      'author' => '63',
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'title',
          'target' => 'title',
          'unique' => 1,
        ),
        1 => array(
          'source' => 'description',
          'target' => 'body',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'url',
          'target' => 'field_feed_source',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'author_name',
          'target' => 'field_feed_author',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '1',
      'update_non_existent' => 'delete',
      'input_format' => 'full_html',
      'skip_hash_check' => 0,
      'bundle' => 'feed_news_item',
    ),
  ),
  'content_type' => 'feed',
  'update' => 0,
  'import_period' => '1800',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
);

And although it runs and imports the articles, it does not create the nodes as my custom content 'Feed News Item' - it always creates them as the default 'Feed Item'

I don't see (or understand) how the Feed links to the Importer - I can't see an obvious link between the two, so it's possible I have missed something!


texts: Set from e-mail address for new user registration only?

texts:
In Drupal 7, it's quite easy to change the body of the emails here:

/admin/config/people/accounts

However, it has no place to set the "from" email address. I'm getting lots of spam signups and want the from email address to be "noreply@mysite.com", so as to make any responses get disgarded.

Any idea how to do this? Or even what email address is set for these emails?


texts:
I am converting a simple module from Drupal 7 to Drupal 8 and I used the Drupal Module Upgrader to do this. The code has been reformatted and some @FIXME notes have been added, I have no experience developing modules though and I'm not sure what to do.

When I search for more info concerning my problem I found this link https://www.drupal.org/node/2346779 but I'm not sure how to rewrite my code snippet exactly.

This is the .module file.

/**
 * @file
 * The littlurl module does little urls.
 */

/**
 * Implements hook_menu().
 */
function littlurl_menu() {
  $items['n'] = array(
    'title' => 'Forward n to node',
    'access arguments' => array('access content'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  $items['u'] = array(
    'title' => 'Forward u to user',
    'access arguments' => array('access user profiles'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  $items['t'] = array(
    'title' => 'Forward t to taxonomy/term',
    'access arguments' => array('access content'),
    'page callback' => 'littlurl_forward',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Page callback to forward people along their merry way.
 */
function littlurl_forward() {
  // Get the elements of the URL.
  $args = explode('/', $_GET['q']);

  // Get the elements of the query string.
  $query_string = $_GET;
  unset($query_string['q']);

  if (count($args) > 1) {
    switch ($args[0]) {
      case 'u':
        $args[0] = 'user';
        break;

      case 't':
        $args[0] = 'taxonomy/term';
        break;

      case 'n':
      default:
        $args[0] = 'node';
        break;
    }
    // It's easier to use url than deal with drupal_goto's arguments.
    // @FIXME
// url() expects a route name or an external URI.
// $destination_url = url(implode('/', $args), array('query' => $query_string, 'absolute' => TRUE));

    drupal_goto($destination_url);
  }
  else {
    // This should never happen.
    drupal_goto('<front>');
  }
}

This is the Controller.php file. It has the same code the .module file has. Should I remove the redundant code snipped from the .module file?

/**
 * @file
 * Contains \Drupal\littlurl\Controller\DefaultController.
 */

namespace Drupal\littlurl\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Default controller for the littlurl module.
 */
class DefaultController extends ControllerBase {

  public function littlurl_forward() {
    // Get the elements of the URL.
    $args = explode('/', $_GET['q']);

    // Get the elements of the query string.
    $query_string = $_GET;
    unset($query_string['q']);

    if (count($args) > 1) {
      switch ($args[0]) {
        case 'u':
          $args[0] = 'user';
          break;

        case 't':
          $args[0] = 'taxonomy/term';
          break;

        case 'n':
        default:
          $args[0] = 'node';
          break;
      }
      // It's easier to use url than deal with drupal_goto's arguments.
      // @FIXME
      // url() expects a route name or an external URI.
      // $destination_url = url(implode('/', $args), array('query' => $query_string, 'absolute' => TRUE));

      drupal_goto($destination_url);
    }
    else {
      // This should never happen.
      drupal_goto('<front>');
    }
  }

}

This is a routing.yml file. It seems to be linking to the controller.

littlurl.forward:
  path: /t
  defaults:
    _title: 'Forward t to taxonomy/term'
    _controller: '\Drupal\littlurl\Controller\DefaultController::littlurl_forward'
  requirements:
    _permission: 'access content'


texts: Does drupal_add_css not load duplicate filenames by design?

texts:
If I try to add a css file using drupal_add_css to a custom module where there is already a css file loaded with the same name elsewhere (in my case in the theme, based on Zen), the module version does not load at all. Nothing to do with overriding styles - the two files contain completely different style information. If I change the filename in the custom module to something else which does not conflict, it loads correctly.

The question is is this by design? If not, is it a known bug? In my opinion this should not happen as a module developer has no idea what css files will be called in any custom theme.


texts:
I'm trying to extract the currency code for the current order, I printed the $order variable using print_r, but I'm not at all a PHP programmer and I don't really know how to extract the currency code, I can see it there, but I don't know how to extract it, can somebody point me to the right direction? I will be delighted if I will learn how to do this kind of actions.

Thanks for your time!


texts: Put the access callback function in a separated file

texts:
When I put the access callback function in a separated file I get an error.

$items['node/%node/join'] = array(
    'title' => t('Join Game'),
    'page callback' => 'agentweb_membership_join',
    'page arguments' => array(1),
    'access callback' => '_agentweb_membership_join_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'join.page.inc',
);

When I put _agentweb_membership_join_access() in join.page.inc I get an error, but when I move it to agentweb_membership.module everything works correctly.

Why does it happen?


texts:
I'm trying to create a webform that has an entity selection element linked to an entity reference view that has a selection of products from the commerce module listed. So far this has all been accomplished.

The entity selection entity displays the product names that you can choose from (unlimited values allowed)

I need to display the total price of the selected products on the confirmation price adding and giving me a total number of all the selected products within that entity selection element.

Is this possible? And where and how would I start?

(v. D8)

If helpful, here are machine names used in the entity reference:

(Commerce)
Product name:  field_product_name
SKU:  field_sku_feature
MSRP:  field_msrp

(Webform)
Entity select: sku_select


texts: Set default values for billing information

texts:
With Drupal 8 and Drupal Commerce 2, I need to set the default values for checkout/billing information. I need to get values from connected user fields.
How could I achieve this?
In Drupal 7 I did this implementing hook_form_alter() and modifying the form, but in Drupal 8 the billing information is contained an entity (Profile) and I can't find where to put the default values.
I feel like in hook_form_alter() I could create a new Profile entity, set fields from user fields and then set this Profile entity as default value for the billing information form. Is this correct?
There is a post about modifying the profile form (billing or shipping) in order to reload an old profile, set one as default or modifying an existing profile
Unfortunately in my use case its useless. I allow only one billing profile, and I need to provide default values from user fields.


texts:
I have refactored an old Drupal 6 site to Drupal 8 and my only problem is, i migrated the users but the password is incorrect. i know that the password in Drupal 6 is a MD5 hash, but i cannot find a solution to convert this password, that Drupal 8 can read it.

Is there any solution for the password migration yet? can i give the MD5 hash a prefix inside of the database to make it readable?


texts: Rules: How to send an email when an OG membership field changes its value?

texts:
I have some OG groups in my site. Each group is an online classroom.

The membership has a few fields (I use the default membership), and one of those fields is a select field with "approved" or "not approved" information about each student's final exam.

I would like to use rules to send an email to each student that change that OG membership field status to "approved". I want this workflow only for users of "exchange-student" role.

But I cannot do that because it seems that I didn't fetched the OG membership. I don't know what I'm doing wrong here.

This is my Rule:

Event:

After updating an existing og membership

Conditions:

Entity exists by property (Parameter: Entity type: OG membership, Property: Exam, Value: Approved)

User has Role
(Parameter: User: [site:current-user], Roles: exchange-student)

Action:
Send a message
(Parameter: Receptáculo: [site:current-user], Private message author: [site:current-user], Private message subject: Aprobaste, Private message body: Mensaje de Prueba)

What am I doing wrong? What am I missing?

Thanks for your help.


texts: I am working in drupal8.I have created five forms all belonging to a single content type.i have around 50 fields in this content type.I have ten fields in a single form.This form has to be filled by the applicant.For each form we have given 20% completion.If i fill one form i shld get 20% completed.If i fill next from i shld get 40% completed and so on.I have created my form and basic crud operations are done.i dont know how to give this percentage of completion.Plz can anyone suggest how this completion percentage has to be done.


texts: How to change the url alias after a username change?

texts:
I'm using pathauto to username paths (/member/[username]). After changing a username the url alias doesn't change and the user edit page doesn't have an option to change it manually.

Is it possible to change it with a rule?


texts: How to find all inputs that make use of the php input filter to fully disable the php filter module?

texts:
I want to disable the PHP Filter module on a large website, but going through all nodes, blocks and other fields where you could make possible use of the php filter would take eons.

Is there a simple way or method maybe by running SQL queries to find out where the php filter is used throughout my website?


texts: Table locking again, am I doing it correct?

texts:
I had a problem with table locking, solved in this question:

Table 'watchdog' was not locked with LOCK TABLES on custom module

I want to share my current code, because I'm still not sure if I am doing it correct.

I have two tables:

eventi_list, for storing users reservation for selected event if there are free places of this event
eventi_wait, for storing users reservation if there are no free places for selected event. If any user withdraw her/his reservation, the oldest reservation for current event (if exists) from this table move to eventi_list table.

function eventi_book($nid) {
    $nid = (int) $nid;
    if (_eventi_if_node($nid)) {
        global $user;
        $uid = (int) $user->uid;
        $is_booked = _eventi_is_booked($uid, $nid);
        if (! $is_booked) {
            $is_booked = _eventi_is_booked($uid, $nid, 'eventi_waits');
        }
        if (! $is_booked) {
            db_query('LOCK TABLES content_type_event WRITE, eventi_list WRITE, eventi_waits WRITE, watchdog WRITE');
            $amount =  _eventi_places_amount($nid);
            if ($amount > 0) {
                _eventi_add($uid, $nid);
                db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");
              //  cache_clear_all();
            } else {
                _eventi_add($uid, $nid, 'eventi_waits');
            }
            db_unlock_tables();
        }
    }
   // _eventi_redirect_to_prev();
}

function _eventi_if_node($nid) {
    $query = db_query("SELECT COUNT(nid) as count FROM {node} WHERE nid=$nid AND type='event'");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_is_booked($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $query = db_query("SELECT count(nid) AS count FROM $tbl_name WHERE nid=$nid AND uid=$uid");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_places_amount($nid) {
    $query = db_query("SELECT field_event_places_amount_value AS amount FROM {content_type_event} WHERE nid=$nid");
    $result = db_fetch_array($query);
    return (int) $result['amount'];
}

function _eventi_add($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $t = time();
    return db_query("INSERT INTO $tbl_name (uid, nid, created_at) VALUES($uid, $nid, $t)");
}

I want to make sure that I never end up with negative number of free places of selected event.
So I have to atomic access to places amount:

$amount =  _eventi_places_amount($nid);

and then I can update places amount, when I am sure that $amount is greater than 0:

db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");

I don't like this solution, because I must to lock many tables. Is there a better way of doing this in Drupal?


texts: Get directories & files of a theme in module

texts:
How can I scan a directory and its files from a module? Is there any permission issue?
I have to apply some logic based on the folder structure in the active theme.

When I use the below code, its returning empty

file_scan_directory($path,$depth=0);

I am getting the path to theme by below code:

$path = base_path() . drupal_get_path('theme','sandesh').'/'.'layouts';

Is this the wrong method to this? Or is there any other apis for that.


texts: How to add another entity type to Search API multiple types index?

texts: I created a multiple types index using Search API. Now I would like to add another entity type to it, but it's not possible. Is there any solution? I really would like to avoid recreating the index.


texts: Using panels to create a custom translation page?

texts: I want to create a page with the translation form side by side with the node being translated. I figure the easiest way to do this would be with Panels but I can't figure out how. Is it possible to put the translation form on a panel?


texts: Form #after_build is not working for PHP 7x

texts:
I'm using #after_build in one of my custom module form like follows

  $form['profile_image'] = array (
    '#type' => 'managed_file',
     '#after_build' => array("change_pic"),
  );

and the function is

function change_pic($element, &$form_state, $form) {
  if($form_state['values']['profile_image']['fid'] != 0){
    // my code goes here..
    return $element;
  }
}

It's working fine in PHP 5x version. but throws the following error in PHP 7x version.

  ArgumentCountError: Too few arguments to function change_pic(), 2 passed
  How can we handle this in PHP 7?

Any inputs would be helpful.


texts: How to publish in an organization with hierarchy?

texts:
My Drupal experience is limited to a single site with custom content types and standard roles. Please take a look at the use case below, involving content being routed through multiple organizational levels, so there is consolidation at each level and some content being "highlighted" for the next higher level.

My company has weekly activity reports. Each member submits an activity report and then the team lead chooses a few to be submitted to our section manager. Then our section manager chooses a few (from multiple teams) to be submitted to our division manager. Then our division chooses a few (from multiple sections) to be submitted to our top level manager.

What stuff should I look into to accomplish content going through different levels like this?


texts: How can I strip HTML tags from views filter autocomplete labels?

texts:
I have an autocomplete widget option. A view is created with exposed filter for free tagging with autocomplete option. However the results provided via suggestions when entering a tag has HTML tags, in particular <p> or <strong> tag.

Is there a way that the tags can be stripped off and trim number of characters?


texts: Views pager not displaying after slideshow image was deleted

texts:
Long story short, I followed both of the guides that can be found here: https://www.youtube.com/watch?v=sXh8Ng9QNaA

I made a couple of adjustments, however.

I set it up as a block instead of a page so I could display other content on the page
I published the images so that users could view the full picture when they clicked the links

Everything worked fine until I deleted one of the images in the slideshow (it was a placeholder). Now the pager doesn't display at all for the slideshow.

I've looked on here, Drupal forums, etc., to see if any questions similar to this have been asked before, but I don't seem to be having much luck.


texts:
I have field structure in Views page. And i want add a image every page item. But not want create img field.,

I search this options in my Views, found 'custom text' option but not found a solution.

Is it possible? How? Thank you.


texts: View to show user relationships with different fields

texts:
I am using the User Relationships module to allow users to forge relations between themselves. The relationship is 1 way of type Following. I have been able to do so. Now i want to create a view for the logged in user which would show him or her their pending relation request, the people they are following, and the people who follow them I tried to do so using Views and contextual filters and adding different fields but was unable to successfully do so. My use case is :  http://i.imgur.com/oYEQzUa.jpg

Thanks


texts: How to add /admin/people as a tab to a custom menu?

texts:
In a custom module (association), I ceated views that are accessible thru tabs:

The paths are defined in the views;

Adhérents et personnes -> /association (this one is also defined as a
menu item)
Adhérents -> /association/members
Personnes -> /association/persons

I'd like to add /admin/people as a fourth tab.
How can I do that?


texts: Get future node id (nid) of nodes being programmatically created (future node)

texts:
I want to create multiple nodes using one form, but I'd like to have connection between them stored in Entity Reference, so I need to know their nids. But they aren't created yet, so they hasn't nids.

Question: Is there a way to predict future nodes nids and preserve them for a while or do something similar to deal with task above?


texts:
I am using drupal core 8.4.2 and lightning 8.x-2.23. I can embed images inside Ckeditor using entity embed. I need to change the name of the data align class from this:

<figure="embedded-entity align-right">

To this:

<figure="embedded-entity floated-element float-right-sm">

Where is the class name align-right coming from and how can I change it?


texts: How to count the number of checked Checkboxes with Rules?

texts:
I have a Drupal Commerce site which uses user points (= coins) for paying.

I have a special case - the product, which the user should buy with his/her coins, needs some fields filled out by the user. So I used a content type for this case and when the user adds a new one, 10 coins will be reduced from the user's account - this works already fine.

Now I have also a taxonomy in this content type and the user can add terms to it, which are shown later in the form when the user fills it.

Problem :

I need to count how many checkboxes of the taxonomy terms are checked and multiply the costs with them. So if 3 of 5 are checked, then 10 coins * 3 = 30 coins will be the final price when the user adds a new content type.

Is this possible with Rules? I have no clue how to realize that
(I´m front-end developer and no PHP coder).


texts: How To Create a Remote Views Search Form - D7

texts:
I have overridden the default Drupal /search page with a panel view that is listing users. In this view, users can be filtered by gender, age, location, etc - and it's working quite well! I have paired Contextual Filters and exposed Filter Criteria enabled to allow GET variables to be passed to the view while still allowing for a Filter Criteria fallback. Achieving this took a few experimental patches.

Now I need to place a search form on the home page that has a few of these filter options. This form needs to direct users to the /search page and take with it whatever the user enters. I've tried using the Exposed Filters Block but doing so removes the filters from the /search page entirely and negates the view header and footer which are unfortunately essential to the view.

Creating a basic HTML GET action form that sends users to the /search page works well, but that's a nasty long URL and I would prefer to keep this within Drupal. It seems that changing this form to use POST instead of GET does not work.

Is there some way to create a stripped-down form that leads into this search view? Using the Forms API would be nice but I'm open to any other solutions presented.


texts: How to use devel on a taxonomy term page to see available nid's?

texts: I'd like to get nid of a node associated with my taxonomy term page, So i'd like to use devel module to see the structure of taxonomy term page.


texts: How can I get the filesize of an image with an image style programmatically

texts:
I need to make two links for an image, one link points to a low res version the other to the original file.

I'm creating the link for the low res with image_style_url

<?php print image_style_url('img-lib', $data->field_field_photo[0]['raw']['uri']) ?>

How can I print out the filesize of the image with img-lib style?


texts:
How can I speed up my complex views? I don't want to remove functionality from my views to speed them up. Some of my views have 5 lefts joins. Is there anything I can do to optimize these queries?

Here's an example: http://i27.lulzimg.com/214ce7e242.png

Here's another one: http://i27.lulzimg.com/5c1d52ab2d.png


texts: How can I detect whether the install process is running?

texts:
I'm looking for a way to reliably detect whether Drupal's install process is currently running, either via drush site-install or install.php.

The immediate problem I'm trying to solve is that I have some settings (using Redis as cache backend) in settings.php which cause the installation to fail. So I'd like to wrap that block of settings in something like if (!drupal_installation_is_currently_running()) { … }

I have not managed to figure out how that can reliably be determined. Any suggestions?


texts:
I have content type name "applicant profile" which all the applicant need to fill up their details and information in this content type..the title for this content type is based on applicant name..
i want to make another content type name "pitch" which have computed field type..

My question..
Since "applicant profile" title is based on applicant name,how i want to display the name of node from "applicant profile" base on user id in computed field for "pitch" content type??
I prefer to retrive the data from "node" table in database..
Can someone help me on how to set the coding for computed field..thank you..


texts: My tab links turned into /user/%/edit, node/%/edit, etc

texts:
Links on tabs turned into /user/%/edit, /user/%/contact, node/%/edit, admin/structure/types/%/fields, etc.
Also, the links on Administration Menu module have the same issue.

Here's what I did so far.

I've cleared all cache via Admin Menu -> Flush all cache, via Development -> Performance and via emptying MySQL cache_* tables. Didn't solve.
I noticed that tabs are themed by the menu_local_tasks() function. I traced the function to includes/menu.inc, where I found the following snippet, which makes me think it might be related to this function.

* For example, the ancestors of node/12345/edit are:
 * - node/12345/edit
 * - node/12345/%
 * - node/%/edit
 * - node/%/%
 * - node/12345
 * - node/%
 * - node

UPDATE:
Where is '%', of the above URLs, being populated? I want to be able to trace it.


texts: How to process an http request with a controller?

texts:
I try to write a custom Restful API to send contents between two drupal site. The present code work except the datas are in a weird format with @ in the json.

My resquest is:

$serializer = \Drupal::service('serializer'); $data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);

$response = \Drupal::httpClient()
        ->post("http://site1.test/api_test/send_content", [
          'headers' => [
            'Content-type' => 'application/json',
          ],
          'json' => $data,
        ]);`

The function which process my request:

public function createNewContent(Request $request) {

   if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {

     $data = json_decode( $request->getContent() );

     \Drupal::logger('test_rest_api')->notice($data);
   }

   $response['data'] = 'Query well received';
   $response['method'] = 'POST';

   return new JsonResponse( $response );
}

The problem is, after the json_decode my datas let a big string and look like:

  @"nid":[{"value":5197],"uuid":[@"value":"8310f782-06ce-4fb8-957d-ec7feecc8929"],"vid":[@"value":63527],"langcode":[@"value":"en"],"type":[@"target_id":"page","target_type":"node_type","target_uuid":"189f826c-e516-4a22-8d4d-f3a2f418aea9"],"revision_timestamp":[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"],"revision_uid":[@"target_id":1,"target_type":"user","target_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"],"revision_log":[],"status":[@"value":true],"title":[@"value":"Test"],"uid":[@"target_id":1,"target_type":"user","target_uuid":"3e68a310-1da4-4691-8501-854c329d9899","url":"/fr/user/1"],"created":[@"value":"2017-12-19T21:07:57+00:00","format":"Y-m-d\TH:i:sP"],"changed":[@"value":"2017-12-19T21:08:36+00:00","format":"Y-m-d\TH:i:sP"],"promote":[@"value":true],"sticky":[@"value":false],"default_langcode":[@"value":true],"revision_translation_affected":[@"value":true],"moderation_state":[],"content_translation_source":[@"value":"und"],"content_translation_outdated":[@"value":false],"metatag":@"value":{"title":"Test","og_site_name":"Test","shortlink":"http://site1.test/en/node/5197/sendContent","canonical_url":"http://site1.test/en/node/5197/sendContent","og_type":"article","og_url":"http://site1.test/en/node/5197/sendContent","image_src":"http://site1.test/sites/default/files/styles/header_full/public/medias/img/hero_pr4_0282.jpg?itok=kSm8zY0q","og_title":"Test","og_description":"This
  is a
  test","og_image":"http://site1.test/sites/default/files/styles/header_full/public/medias/img/hero_pr4_0282.jpg?itok=kSm8zY0q","og_updated_time":"2017-12-19T16:08:36-05:00","article_published_time":"2017-12-19T16:07:57-05:00","article_modified_time":"2017-12-19T16:08:36-05:00"},"path":[@"alias":"/test","pid":16287,"langcode":"en"],"rh_action":[@"value":"bundle_default"],"rh_redirect":[],"rh_redirect_response":[@"value":301],"publish_on":[],"unpublish_on":[],"menu_link":[],"body":[@"value":"\u003Cp\u003EThis
  is a test\u003C/p\u003E","format":"full_html","summary":""]}

I precise the @ are already present before the json_decode. I don't know where I could have made a mistake.

I suppose I can clean it easily but I'm more interested to understand what is this format and how can I convert it properly and quickly.


texts: Uploading file, parsing and displaying data

texts:
For a site i am building right now, there is one component that I would want the user to upload a file, where it will be parsed (currently a python script, but can be ported to something else). The data from the parser will then be used populate a node.

what will be the best way to go around doing this?
rules to start the parsing and feeds to import the data?
a custom php page?
or a custom mod to generate the display i want from the file uploaded in the same node?

need some guidance >,<


texts: OG group - Edit permissions of groups for specific role

texts:
I don't have too much experience with OG so I would be glad if someone could help me. Basically scenario is:

I use organic groups for microsite creation, so I have a content type which is called "Microsite" and it is set as a og group. I have some other content types which can belong to the group.

I want to create a role "Microsite admin" who will be able only edit existing groups (in this case microsites) and only specific fields which are on the microsite content type (This part I think I can solve with field permission module)

Og allows only group manage edit a group or someone who belongs to the group and have permissions to edit it.

In my case I want to have a one global role who will be able edit all groups and specific fields on it. (So basically someone who doesn't belong to any group and have admin permission to edit them).


texts: Saving a field of type 'text_format' as a system setting variable

texts:
I'm attempting to give my content editors the ability to change a variable for a custom module. This variable can have html. I don't want to require them to have any knowledge of HTML, so I want to give them the ability to have our wysiwyg (CKEditor provided by the CKEditor module) at their disposal. However, as of now, the data does not save as a variable. I've read in a few places (D.o, stackexchange) that I needed to do something like this:

  $form['foo']['bar'] = array(
    '#type'     => 'text_format',
    '#title'    => 'Bar',
    '#definition' => 'Foo Bar',
    '#default_value' => variable_get('bar', ''),
    '#weight'   => 1,
    '#format' => 'filtered_html',
    '#required' => FALSE,
  );

This does not work out-of-the-box with a system_settings_form($form). A var_dump shows this after a save:

array (size=7)
  '#type' => string 'text_format' (length=11)
  '#title' => string 'Bar' (length=7)
  '#definition' => string 'Foo Bar' (length=74)
  '#default_value' =>
    array (size=2)
      'value' => string '' (length=0)
      'format' => string 'filtered_html' (length=9)
  '#weight' => int 1
  '#format' => string 'filtered_html' (length=9)
  '#required' => boolean false

From this, you can see that 'format' saves correctly, but 'value' does not. What am I missing?

Also, if there is a better way to do this, please do tell.


texts: Theming mini panel using MYTHEME_preprocess_panels_pane

texts:
I'm trying to edit the content of a mini panel using MYTHEME_preprocess_panels_pane but when I use Devel to dsm $variables, I just get data for the pane that holds the mini panel.

Is there a function to get into the mini panel?

At first I thought hook_panels_pane_content_alter might work but I'm getting nothing when I drop it into my template.php


texts:
I've set up my Drupal installation as a Service Provider using Simplesamlphp and the Drupal Module Simplesamlphp Authentication (https://www.drupal.org/project/simplesamlphp_auth).  I'm successfully able to login using the www.example.com/saml_login method provided, but I haven't been able to setup the automatic role assignments.

From this page:
https://www.drupal.org/node/1931394

I've attempted comment #3 but was unable to get it to use the friendly name.  Here is what is being sent to me from my IDP:

<saml2:AttributeStatement>
         <saml2:Attribute FriendlyName="uid"
                          Name="urn:oid:0.9.2342.19200300.100.1.1"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >landy</saml2:AttributeValue>
         </saml2:Attribute>
         <saml2:Attribute FriendlyName="eduPersonAffiliation"
                          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >member</saml2:AttributeValue>
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >staff</saml2:AttributeValue>
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >employee</saml2:AttributeValue>
         </saml2:Attribute>
         <saml2:Attribute FriendlyName="eduPersonPrincipalName"
                          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.6"
                          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
                          >
             <saml2:AttributeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xsi:type="xs:string"
                                   >landy@uab.edu</saml2:AttributeValue>
         </saml2:Attribute>
     </saml2:AttributeStatement>

But I'm unable to get it to automatically populate the role.  As an example, I've tried this:
3:uid,=,landy

It's never assigned him to RoleID 3.  I've been able to do this from the Rules module, but I'd like to be able to use it in this module if possible because the eventual plan is to use those Affiliation attributes as well which Rules cannot use.  Thanks for any help!


texts:
I'd like to modify the current order layout visible at user/[uid]/orders/[order_id]

Specifically, I'd like to list the billing and shipping info before the line item detail:

billing and shipping
List item detail
subtotals

I know that the the line item detail is a View that can be edited, but I'm not sure how to control placement/sequence of items not in this view.

Thanks in advance for any tips or advice.


texts: Add a CSS basing on the author of the comment

texts:
This node has a comment by the user #1, who is the node author, and a comment by an anonymous user. I want to add an extra CSS class to comments by the node author.

The variables in Bartik's comment.tpl.php include $author and $comment-by-node-author.

What is the correct syntax for an if statement saying if this comment is by the node author (or by user #1) apply the class example and just print the comment as usual when the author is somebody else?


texts: Get form element's label/value pairs from &$form or &$form_state

texts:
I need to pass an array with all the fields (with their values) from a form from the submit function to a rules_invoke_event.

to do this I'm calling a get_fields() function, in this function I have acces to the form and form_state objects. Just wondering how I could loop through one of these with a foreach to get an array with the pairs?

function get_fields($form, $form_state)
  $fields = array()
  foreach(element in form)
  {
    $fields[$element[key]] = element[value];
  }
  return$ fields
}

something like this but with correct syntax?

Help would be greatly appreciated :)


texts: Need to alter response headers for error pages

texts:
We have Cloudflare sitting in front of our Drupal sites - and in order to take advantage of their "AlwaysOnline" feature - we need to alter the response code sent in the event of an error.

I want to cater for when the database is unavailable - as this can sometimes happen when upgrading the MySQL server.

The only way I've found so far is to hack the errors.inc file:

if ($fatal) {
    drupal_add_http_header('Status', '504 Service unavailable (with message)');
  }

Is there a more elegant way to achieve what I'm after?


texts:
I have a custom entity with several fields. Now I would like to group the fields and give each group it's own twig template so that I would be able to compose a page (my custom entity) containing several sections (field groups).

How would you do that? Do I group the fields in the entity preprocess function and give each group it's own '#theme', do I have to change my hook_theme or should the grouping already happen in the controller? Or maybe create a computed field to store the other fields?

Thank you in advance!


texts: Importing existing users into a new Drupal site

texts:
We have an existing Drupal site that has a requirement to inherit about 10k users into, and we've been able to gather most of this data through CSV exports on the Database, and Views Export/VBO. What we have is two CSVs, one with usernames, password hashes, UIDs; the other with user field data and a UID to join/union the data during import. There are differences between the Field structure between the site data we inherited and the new site, so new data relationships will need to be established during the import, ruling out a direct port of the existing Database records.

I have no issues writing a Drush script that will import all the users with a joined CSV. What I am wondering is if its possible to import the user records, complete with the password strings within the Drupal User space. Looking at the user_save() method its not clear as if I can define the User ID, or password hash. And we have a lot of logic implemented that depends upon this

So the approach I have in my head is this:

Use SQL IN FILE to import the baseline minimum data to establish users in Drupal's users table: Username, Password Hash, created date, changed date, etc...
Use a second drush script to iterate through the field data, and update the user records with user_save() off UID.

Is there another approach I can use that's strictly Drush based? This assumes that the data I import will be with a Unioned CSV file. Not being able to adjust the UID probably means this isn't possible, but its worth asking.


texts: Which table does the Phone module store data in?

texts:
I have installed the Phone module to create a field to take input data as mobile number.

I would like to fetch the mobile number back from database to be displayed in a block. I am not getting the table in which the phone number is stored. So in which table is the phone number data is stored?


texts: My theme's page.tpl.php has made my user login form disappear at mysite.com/user

texts:
I was able to create
page--user--login.tpl.php with this code in it:

Forget your password? | Create an account

<?php
    // render login button
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
print drupal_render($form['actions']);
?>

I can log in but ONLY if I do so at mysite.com/user/login

No login form appears if I go to mysite.com/user

Once I do log in, no information appears at mysite.com/user/coral  (coral being the login name in this case)

In every drupal site I've ever logged into, I do so at mysite.com/user.  What do I need to do to get these pages to work again?

Or... is there a way to have these pages use Bartik instead of my custom theme?  It doesn't really matter how they are styled.


texts: IS there a replacement for 'taxonomy_node_get_terms_by_vocabulary' in Drupal 7?

texts:
The closest I have come is taxonomy_term_load_multiple but the conditions argument will be deprecated in V8.  They now recommend EntityFieldQuery as a replacement.  I am new to coding and have not worked with setting up the conditions for the query and am having trouble finding documentation/tutorials.  If a simpler function exists, I would prefer to use it.  Answers addressing a function or how to use EntityFieldQuery are welcome.

Thanks


texts:
I'm working on a payment gateway, so I've created a BasePaymentOffsiteForm form where I'm trying to make an ajax callback, but it is not working.
Can you help me to know what is wrong with my code?
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['content'] = [
      '#type' => 'container',
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    $form['content']['mobile_phone'] = [
      '#type'   => 'textfield',
      '#title'  => $this->t('Mobile phone'),
    ];

    $form['content']['validate_client'] = [
      '#type' => 'button',
      '#value' => $this->t('Validate Client'),
      '#ajax' => [
        '#callback' => [get_class($this), 'clientValidateForm'],
        'event' => 'click',
        'wrapper' => 'validate-phone-number',
      ],
    ];

    $form['content']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromUri($form['#cancel_url']),
    ];

    return $form;
  }

  public static function clientValidateForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Pay',
    ];
    return $form['submit'];
  }

It never gets in cientValidateForm method.


texts: Create defaults for panels to be deployed on install only

texts: We have a mini panel that we use to create a footer area. This is deployed on install of a new multi-site through our custom installation profile. I would like to set default content items in the panel regions on install. If I were to do this in a feature, then any changes made by the site administrator would be reverted on a features-revert-all command. How do I go about creating this as part of an install file?


texts:
I'm trying to add an "add more" field to a form in my custom module. I've been looking at the examples module, with no luck.

Here's what I have so far:

$form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '
',
  '#suffix' => '
',
);

if (empty($form_state['num_names'])) {
  $form_state['num_names'] = 1;
}

for ($i = 0; $i < $form_state['num_names']; $i++) {
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
}

$form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('spower_add_more_add_one'),
  // See the examples in ajax_example.module for more details on the
  // properties of #ajax.
  '#ajax' => array(
    'callback' => 'spower_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);

if ($form_state['num_names'] > 1) {
  $form['names_fieldset']['remove_name'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#submit' => array('spower_add_more_remove_one'),
    '#ajax' => array(
      'callback' => 'spower_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
}

function spower_theme($existing, $type, $theme, $path) {
  $base = array(
    'render element' => 'form',
  );

  return array(
    'spower_my_form' => $base + array(
      'template' => 'spower',
    ),
  );
}

function spower_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function spower_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function spower_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

The problem is that when I click "add more", the entire form is submitted.

If the above isn't clear, I've added the module at http://pastebin.com/Hn7bkM2v and the spower_elements.inc at http://pastebin.com/CwHW5mSm.

Thanks for the help.


texts:
I am trying to create a custom Webform element that can be added to any webform. It is a select list, but I am providing the options from a remote API call (they cannot be static or hardcoded).
I can get the element to appear in the admin UI with:
use Drupal\webform\Plugin\WebformElement\Select;

/**
 * Provides a 'tour type' element.
 *
 * @WebformElement(
 *   id = "tour_type",
 *   label = @Translation("Tour Type"),
 *   description = @Translation("Provides a form element to list tour types from Funnel."),
 *   category = @Translation("Options elements"),
 * )
 */
class TourType extends Select {

}

I can add it to a form, and give it options like a regular Select in Webform, but nothing renders on the form.
I was trying to follow this here, but don't quite understand what needs to be done: Why do my custom elements not get rendered?
Do I need a WebformElement plugin, or a new Element class? I don't see how the two are correlated.


texts: File uploads: Warning: session_start(): Cannot send session cookie - headers already sent

texts:
When I check watchdog, I have lots of PHP warnings like this:

  Warning: session_start(): Cannot send session cookie - headers already
  sent by (output started at
  /srv/bindings/9c42927e5316467d82a6fb1be50ed34e/code/includes/file.inc:1972)
  in drupal_session_start() (line 287 of
  /srv/bindings/9c42927e5316467d82a6fb1be50ed34e/code/includes/session.inc).

There are a lot of reports of errors like this, apparently most of which are caused by having spaces at the beginning or ends of PHP files.  But in this case, I think the problem is related to file uploads for the following reason.  The Location of these warnings are paths like this:

  https://example.com/sites/default/files/styles/profile_pic/public/pics/41207/image.jpg?itok=cdQrU8Rv

The Referrer is my "manage pictures" page, which allows users to add a Picture content type which includes an Image field.

So, it looks like session_start() is having trouble during uploads.  Is there a standard fix fox this kind of problem?


texts: Get taxonomy field value in forum-list.html.twig

texts:
I am customizing the appearance of the forums.
I added all my forums and container. Additionally, I added a custom taxonomy field I need to show for each forum category.

How can I show the custom taxonomy field in forum-list.html.twig?
I know how to show content fields from nodes in node.html.twig, but how do I show custom taxonomy fields in forum-list.html.twig?


texts: Calendar - Non repeating events displaying in multiple months, how to fix it?

texts:
I have normal events which are displaying correctly in the month they should but they also appear in the first line (week) of each month after.

I have tried removing the events and creating them again, creating the calendar from scratch but still they appear.

I'm not sure what extra details would help in answering this so if there is anything you need just let me know.

Thanks


texts: BrowserTest on a multisite gives an error

texts:
My sites directory looks like this:

default, site1, site2, site3.

The default directory is empty. I want to run tests against my site1 database. So I have put its details in phpunit.xml

Here is my phpunit.xml set up.

  <php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <env name="SIMPLETEST_BASE_URL" value="http://d8.site1.dev"/>
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="mysql://site1:site1@localhost/site1"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/>
  </php>

And then my actual test:

<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;

/**
 * Simple test to ensure that main page loads with module enabled.
 *
 * @group my_module_tests
 */
class LoadTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['my_module'];

  /**
   * A user with permission to administer site configuration.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->user = $this->drupalCreateUser(['administer site configuration']);
    $this->drupalLogin($this->user);
  }

  /**
   * Tests that the home page loads with a 200 response.
   */
  public function testLoad() {
    $this->drupalGet('node/add/product_list_page');
    $this->assertResponse(200);
  }

}

Then from the core directory of Drupal I run:

../../vendor/bin/phpunit --group my_module_group

Then I get this error:

1) Drupal\Tests\my_module\Functional\LoadTest::testLoad
copy(/var/www/site/docroot/sites/default/default.settings.php): failed to open stream: No such file or directory

Why is it looking in my empty default directory and not site1 for this file?


texts: Commerce: Unique single products + Custom line items, How to handle?

texts:
I am building a shop with several types of custom cushions available. Each product (cushion shape) will have different options therefore i am using custom line items.

The issue is that to me it seems i need to create just as many different content types (product display) in order to reference the custom line item in the add to cart form of the Display?

There must be better way to do this?


texts: hook for db insert function on custom table

texts:
Is there any hook on db_insert function on a custom table?

db_insert('projects')
  ->fields(array(
    'title' => $title,
    'p_key' => $projectkey,
  ))->execute();


texts: I am assisting on a D8 site being developed and need to come up to speed as my only experience with Drupal is D6. The D6 site has a custom module/form that queries MSSQL data. It's a relatively simple form that only queries and doesn't store any information. The results are returned as a list, with the ability to drill down to details on any given record. I like what I am seeing so far with the webform module and I think it might fit our needs but I could use a little advice/direction as to connecting the form to the db.


texts:
I was facing an decision about a project. We have a website in drupal 7 that talks about cars. Now we want to talk about motorcycle. The basic layout will be different, i mean the header and footer.

We want to be able for example a user in motorcycle if search for a car can show (if exist) the result  from the cars sites and the link will get him to the main site.

Can we achieve this kind of behavior ?

How i want to look
So we have Option A : moto.mysite.com
Option B will be mysite.com/moto/


texts: Ckeditor Stripping all attributes, when re-editing content

texts:
Ckeditor is stripping out all attributes from the source code.

This is the case I'm going through:
When I add html code to the source of the Ckeditor, and then want to preview the changes by selecting source again, I find that no styling was taken. When I go back to check the source all styling attributes are removed and some HTML tags.

I found a way to save the content, without stripping by directly saving after pasting the html code in the source. But if I try to re-edit the content it strips all styling attributes and some html tags.

I am using Full HTML Text format, and did try previous versions of the ckeditor module. Also tried to modify the config.js file by adding "config.allowedContent = true;" as referred by the following post

  About

    Biography

    Timeline

    Quotations

    Philosophy

CKeditor Stripped HTMl:

About

Biography

Timeline

Quotations

Philosophy

Intellectual Legacy

Any way to resolve the following?


texts:
In "Status report" I have message saying that some modules have database schema updates to install. However, when I run update.php nothing happens. I just get the standard error message that "Some of the pending updates cannot be applied because their dependencies were not met."

Reports -> log messages does not have anything relevant.

How should I debug this?


texts:
I've got 2 roles on my system -uzman and isveren- and several views that need to be restricted to either uzman or isveren. For that purpose, I have been trying to check access control with PHP. I can't use role based access check because then administrator would see all because he has access to all views. Anyway, I am using

<?php
if (in_array("uzman", $account->roles)) {
return TRUE;
}
?>

which works, but I see many undefined offset:4 messages in dblog (4 is uzman's rid). What is the correct way to check access with PHP in Views module?


texts:
I have some content that has state field. I would like to permit users with the same state to delete this content.
Can  I implement this in Drupal?
Can I implement it with PHP code?


texts: How do I associate an uploaded file to an Organic Group?


texts: Close webform modal and redirect to entity

texts:
I have a webform that opens inside a modal. Everything works fine. Then I had the problem of closing the modal after the form was submitted. I fixed that to with the help of the following link: https://www.drupal.org/project/webform/issues/3002966#comment-12794056

I have a webform handler that creates a new entity in the postSave() method. After this entity is created, I want to close the modal and redirect to the entity detail page. What is the best/correct way to do this. I could use a RedirectCommand instead of the CloseDialogCommand but how do I get the entity id in the _CUSTOM_MODULE_webform_submission_form_submit_ajax() method. Using the AjaxResponse with a RedirectCommand in the postSave() method didn't work.

Any Suggestions would be great ;-)


texts: Is there a submit handler for custom fields?

texts: I built a custom field, and now I'm adding an image upload to that custom field.  The type is managed_file.  When the user saves the content, where can I handle the file after submit?


texts: How can I display a token from contextual filter

texts:
I am trying to see if there is a way to pass basically  a contextual token to a panel page. I have a panel page which displays Views blocks of content types based on contextual filter of author real name, but I would like to also generate another block or custom content to display elsewhere on the panel page which displays the author real name and maybe some other profile items.

Is there any way to pass the contextual filter from the view into this type of content?

I have been able to expose the author name, but only as a list which has one entry for each article rather than a field which I could use as a header, etc.

I'm probably missing something basic here, but any help would sure be appreciated. My experience to date has mostly been with displaying current user name, etc. in custom blocks or other content.


texts: How to I add a node reference field using the Webform module?

texts:
Is it possible to add a node reference field using the Webform module?

If it is, how can I add it in my webform?


texts: How do I include tax and discount in computed field?

texts:
I use the Commerce price by components module to display products' commerce_price field with tax and discount included.
It works as expected (I'm displaying the products' prices with a view in a panel)

I have another field, which is a Computed field, that I use to calculate the discount between the commerce_price field and a custom price field (MSRP).

Unfortunately, while the commerce_price is displayed with tax and discount included, the value sent to the computed field (from the commerce_price token) is the original value, without tax or discount applied, or any information related to the price components.

I can't figure out a clean way to apply the tax and the discount to the commerce_field value used for the calculation in the Computed field. How can I make the computed field receive the same token value as the one displayed?

I'm aware of the module Drupal Commerce Extra Price Formatters but using the Computed field gives me way more flexibility to calculate discount and special prices captions.


texts: How to dynamically populate select options?

texts:
I'm trying to build an admin form for a module, using system_settings_form().

I want the users to be able to select sub-options, from a list that is dynamically generated depending on the main option.

For example

$main_options = array('foo','bar');
$sub_options['foo'] = array('foolish','football','foodstuff');
$sub_options['bar'] = array('barley','baroque','barbarian');

$form = array();

$form['main_option'] = array(
    '#type' => 'select',
    '#options' => $main_options,
);

$form['sub_option'] = array(
    '#type'  => 'select',
    '#options' => $sub_options[SOMEHOW USE THE SELECTED VALUE OF main_option AS INDEX],
);

return system_settings_form($form);

So I would expect sub_option to be unpopulated the first time the form is called, and then populated as soon as the user populates main_option.

Is this possible?

Update

Thanks for the advice re Ajax. I looked up https://www.drupal.org/node/752056 and this is what I've built: here the values in olt_test need to change based on the value selected for olt_provider.

  $form['olt_provider'] = array(
    '#type' => 'select',
    '#title' => t('Provider'),
    '#options' => variable_get('providers'),
    '#ajax' => array(
      'callback' => 'olt_provider_select_callback',
      'wrapper' => 'tests-div',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '
',
    '#options' => array(''),
  );

and in olt_provider_select_callback() I have

  function olt_provider_select_callback($form, $form_state) {

  $new_options_value = [new value calculation snipped]

  $form['olt_test'] = array(
    '#type' => 'select',
    '#title' => t('Test'),
    '#prefix' => '
',
    '#options' => $new_options_value,
  );

  return $form['olt_test'];
}

The problem I'm now seeing is that the Ajax only fires on the first time the olt_provider select box is clicked - subsequent clicks don't fire. Any thoughts?

The problem I'm now seeing is that although the olt_test dropdown is correctly updated via Ajax, this replacement value is not saved on form submission. Any thoughts?

Final Update - My form is working correctly now. The data was being saved on form submission, but I needed to add some more code to retrieve the saved data and display the default values when the form was loaded.


texts:
I want to be able to ask users a question, and, depending on their answer, go to some other question. Webforms does not handle this well, since it seems to assume that the user answers most of the questions. I'm looking for something like

What price range do you want?

If between $100 and $200, go to question 2
If between $200 and $300, go to question 3
If between $300 and $400, go to question 4

And so on.

At the end, I need to be able to see all of their answers in order to perform a
DB query, so their responses will have to be "accumulated" as they go. I don't
strictly need to have their answers stored in the DB, but it would be nice. I'm
fine with programming in a hackish special case with hardcoded targets, but a
clicky-button interface would be preferable, if such a module exists.

I feel like there should be some relatively-easy way of doing this, perhaps with
the Form API and fields on nodes, but I can't quite put my finger on how it
would be done.


texts: Create a node(filedepot folder) after user registers in site

texts:
Possible Duplicate:
  How to create new node programmatically, when a new user is created, in Drupal 7?

I am using Drupal-7 and Filedepot module. In Filedepot module a folder is created when we create node of filedepot folder content type.

I want to achieve that when any user registers in the site then one filedepot folder should be created.

Initially I used Rules module. And after registration I created a Rule to create a node of filedepot folder content type, but problem is that by using Rules I can't set some of the fields of content type. Node creation using Rules only creates node and sets title but it doesn't set the values of other fields.

Now I am planning to achieve it using other way, after user registers I want to create a node programmatically.

How can I customize Rule's node create action?


texts: Most Appropriate Way To Implement Complex Configuration Data?

texts:
I need to create admin for content that makes a series of nested references to our separate data API. When a new content-item is created, the user selects one or more data sources from a (large) list. Then they create a list of one or more references to those selected sources. For each reference, they choose from a list of items available for that source. For each of those datasource-item's, they enter a few text fields and zero or more references to attributes available for that datasource. And for those attribute references, they can select one or more from a list of possible values.

The exact structure of this item changes with the project and my knowledge of the Field & Form APIs isn't great. So I have built this functionality with JavascriptMVC and have been serializing JSON into a bare bones Drupal text field.

AJAX forms in D7 seem amenable to building out the form itself, but what should I do with the values? Should I implement content types A, B and C and hook everything together with nodereference fields? That seems heavy and cumbersome to change as the project evolves. I don't know if Entity would be more appropriate or maybe something I'm not aware of.


texts: How to change column chart color programmatically

texts:
I have created view block using different content type. I am displaying this block as a column chart using Drupal module Highcharts, it is working but if I want to display separate color of content type node I mean one color for one content type node and other color for other content type.
Can any one tell me how to change this? Is there any module by which I can sort out my problem?


texts: Is the Drush backend API a web-accessible API? How does one install it?

texts:
I've successfully configured Drush 4.5 to work agains my Drupal 6 site from the command line using site aliases.  I am doing things like sql-sync and rsync successfully from the command line.  What I'd like to do now is expose these functions over the web, through an API.  The Drush documentation leads me to believe I can do this, however it is somewhat lacking in details on how to accomplish this, or indeed whether it's even part of the intended design.

There is a very high chance that I have completely misunderstood the documentation and have assumed a CLI-only API was designed to be available through the web.  However, the backend.inc file talks about a REST API accessible over HTTP and is ambiguous about what this API actually does.

  This is nearly a RESTful API. @see htp://en.wikipedia.org/wiki/REST
  Instead of "http://[server]/[apipath]/[command]?[arg1]=[value1],[arg2]=[value2]"
  it will call "[apipath] [command] --[arg1]=[value1] --[arg2]=[value2] --backend"

It's not clear to me what this actually means, because it says "instead of" the web call, but then goes on to describe how GET and POST arguments differ and how they are passed in from a web call.

  If the Drush API is meant to be called over the web, e.g. http://server.com/drush/drush.php/drupal-directory?argv1=@staging how do I enable this, given that Drush is in a separate PHP source tree?  Do I symlink to it from my Drupal directory?  Do I copy or symlink an include file and expect Drupal to pick it up?


texts: using xhprof in drupal 6 to monitor a cron task and display in the XHProf runs page

texts:
I'm trying to profile a specific cron task in drupal 6 to check the function calls made and what consumes the maximum time and decided to use the XHProf module  which I've never used before. I've got the module successfully installed and able to get the page loads profiled and listed in admin/reports/xhprof.

But to get my cron task to be profiled and listed in it I'm pretty clueless and tried out a few things from what I could gather from PHP.net but beyond coding

xhprof_enable();
echo "
ENABLED
";
// the code block I wish to profile
$xhprof_data = xhprof_disable();
echo "
";
print_r($xhprof_data);
echo "
";

by checking the internet. The $xhprof_data does contain the necessary info array. But I'm not able to get the slightest hint of how this data that's printed could be formatted and displayed like the page loads which get profiled out of the box. Any help on this is greatly appreciated.


texts:
I need to implement hook_views_query_alter() to change the value of delta of the field that form a relationship.

As I posted in change delta value, the code is the following one.

   function supermama_misc_views_query_alter($view, $query) {
     $view->$query->table_queue['field']['join']->extra[2]['value'] = 1;
   }

It gives me the following error:

  Fatal error: Cannot access empty property

The same error appears if I use the following code.

    function supermama_misc_views_post_build($view) {
      if ($view->name == 'gallery_images') {
        $view->$query->table_queue['field']['join']->extra[2]['value'] = 1;
      }
    }

What's wrong with the code? How do I bypass the error?


texts:
I'd like to create a one-off custom page which will contain several text fields.

The layout for the page will be custom, placing the text fields in various locations next to design elements, diagrams and maps. I'd like the site editors to be able to update the text fields/labels, including language versions.

I'm generally familiar with the render API, page and node templates, and I do know that I could create a dedicated content type (node, content entity) with all the fields required and then a page template (Drupal 8 custom page template) to render the node (and its language versions).

Just wondering if it makes sense to create a complete content type for what will effectively be a one-off (albeit important) node/page.

Thoughts? Suggestions?


texts: The 'drupal' way to implement delete button UI

texts:
I think I'm missing something fundamental here. What's the 'right' way to implement a delete button on the UI-end?

My app has a classic list-type data model: User has wishlist(s) -> wishlist has item(s) -> item has properties. (These are represented in several tables, of course).

The several views are loaded via tpl files using hook_theme(). When the app has a view loaded for any step of the way (looking at an item in a list, for instance) I want to have edit/delete buttons that act on the item.
The CRUD methods are in place, they just need to be wired to the button.

In some places in the app, I've exposed methods via hook_menu(), and that works fine by passing the target to l() - I'm using this for many of my "View Item" UIs. Is there another way, though? This seems to be exposing a ton of core logic to the address bar if I keep going that route.

In a nutshell: How do I have a button action similar to pseudocode button.click=$this->bluenose_app_remove_available_property($property->id);? Preferrably without routing through hook_menu()


texts: What causes my PHP error in my custom VBO action using a Rules component?

texts:
I have created a view of unevaluated quiz results and added a vbo field. I created a rule component with action save entity "result" and added the component to the vbo.

When the operation is carried out, it doesn't save the result. But if I add "show message on site", that works.

Enabling debugging, php errors are thrown like so:

  notice: Trying to get property of non object in quiz_access_results() line 186...

I'm using Quiz version 7.x-5.1.

Exported Rules Component:

{ "rules_save_uncompleted_exams" : {
    "LABEL" : "Save uncompleted exams",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "result" : { "label" : "quiz result", "type" : "quiz_result" } },
    "DO" : [ { "entity_save" : { "data" : [ "result" ], "immediate" : "1" } } ]
  }
}

Note: Quiz results are saved at first but are not completed "evaluated" until the entire quiz is submitted. So if a user logs out without submitting, the total score will not be evaluated. By creating a vbo, an admin can manually score all the quizes.


texts: How to display User profile fields to anonymous visitors?

texts:
Currently I am developing an application in Drupal 7 , and my requirement is to display User profiles(profile image,DOB,Course,Year of joining etc.,) to anonymous users . I have used profile2 module to store them in the Database. The same information I wanted to display when a visitor clicks any of the User link. But i stuck in this part.

Please assist me in solving this...!

Thanks in advance
-Syam Kumar


texts: How do you know if user_login_submit was successful in Drupal 7?

texts:
Based on the answer from this question How do I programmatically log in a user?

I know how to login in a user, but is there a way to test if user_login_submit was successful or not? It does not have a return value.


texts: How to embed view in basic page content?

texts:
I want to embed a view in  content of type basic page in D8.
How to I do that. Insert View module is still not stable to be used in D8.


texts: drupal http_request give solr parse exception

texts:
typing a WS uri into the navigator return the json correctly

but the same adress in $url

 $result=drupal_http_request( $url );
 var_dump($result->data);

gives a parse exception

  Cannot parse 'docid:(7000': Encountered \"\" at line 1, column
  11.\nWas expecting one of:\n ...\n ...\n ...\n \"+\" ...\n \"-\" ...\n ...\n \"(\" ...\n \")\" ...\n \"*\" ...\n \"^\" ...\n ...\n ...\n
  ...\n ...\n ...\n ...\n \"[\" ...\n \"{\" ...\n ...\n \"filter(\"
  ...\n ...\n ","code":400}

it must have smthg to do with whitespace or some special characters
because it works with docid:(7000) but not docid:(7000 OR 7001)

How to somehow encode the url so that the solr WS server is happy with my request?

the same url works with drupal 8 code

   use GuzzleHttp\Client;
      $client = new Client();
      $response = $client->request('GET', $url);


texts: How to set up a view that show only the log messages related to the node author

texts:
I'm trying to create a view similar to the Facebook notification that show all the log messages relative only to the node author.

I'm working with message and rules and i've already set a view that display all the website activity like: "user-A likes node-X", "user-A commented node_X" and so on. But I'm going crazy to set up a view that display only those messages related to the node author so that each author can see only the activities related to its nodes.

Is possible to make this kind of filter?


texts: How to sync users profiles and user tables in 2 drupal sites

texts:
I have a website with 14K registered users. There is new section of that website which has been developed as a separate Drupal installation. The users in the old website should be able to login with their username and password to the new site.

My questions are :

is there a way to connect new site "user registration/login/forget
password" features with the old one?
Should i sync the databases all
the time? Or when the new user registers, his information is added
in to new and old site ( and Vice Versa)

What is the best practice in such cases.

thanks :)


texts: Expose some administrative functions on the front-end

texts:
I'm developing a web-app for managing non-profit organizations by extending the functionality of the Drupal CMS. What I want is to have only one administrator account (call it super-admin if you prefer), which should be used only by the developer, next there will be a set of roles (coordinator, director, employee).

The idea is that non of those should be able to perform administrative tasks that may broke the site functionality (like managing blocks or menus), but not just that, to provide a cleaner and more compact interface I would like to expose some functions of the admin side to the front-end (accessible only for determined roles), for example, the coordinator should be able to change the role of an employee in order to upgrade him to director.

Is that possible?


texts: How can I modify the advanced search form when my hook runs too early?

texts:
I'm using hook_form_FORM_ID_alter to modify the content of the form on the search page — I want to remove the "phrase" and "not" fields, and restrict the "only of the types" checkboxes to a hand selected list of types.

I have the following code, which is being called and which I think should work:

function MYMODULE_form_search_form_alter(&$form, &$form_state, $form_id) {
    unset($form['basic']);
    unset($form['advanced']['keywords']['phrase']);
    unset($form['advanced']['keywords']['negative']);
    unset($form['advanced']['type']);
    $form['advanced']['type'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Only of the type(s)'),
        '#options' => array(
            'blog' => 'Blog entry',
            'event' => 'Event',
            'news' => 'News article'
        )
    );
    // print_r($form);
    // die;
}

Except node_form_search_form_alter gets to the search form after my form alter hook runs, so I don't get a chance to modify any of the form elements that it's adding.

I'm running Drupal 7.22.

How can I modify the advanced search form when my module hook runs before the hook that defines the advanced search form?


texts: How do I connect to the database from a module?

texts:
I would like to connect to the database from a Drupal 7 module. Currently I only have the query I want to run which is:

$query = db_select('z_lists)
->fields('country')
->condition('value', $country, '=')
->execute()
->fetchAssoc();

What I can't figure out is how to establish a connection to the default database.

Any help?


texts: How can I submit a blank or "wild card" search query?

texts:
I'm using the Custom Search module to add some taxonomy fields to my site's search form, so I have a form that looks like this:

Business Name [text field]
Categories    [select list]
Towns         [select list]
Price Range   [select list]

It works just fine, however, the search form won't submit unless something is filled in the original search text field. It would be quite useful to leave that blank and simply search for a category and town, or a town and price range.

Essentially I'm looking to add "OR" after the text portion of the query, or a value to insert, in case it's left blank, that will return all results.

Is there a file I can edit or a setting I can adjust to allow this?


texts: BEF - Multiselect option renders checkboxes instead select multiple

texts:
I'm having issues with my VIEW filter, which has only 4 options and is set to allow select multiple options. Therefore Better Exposed Filters (BEF) renders options as checkboxes instead of html select tag. How can I override this behavior, to render options inside (as it behaves when filter has 5+ options)

<select multiple>
    <option>
    ...
</select>