texts:
I'm trying to find a version of Drush that is compatible with Drupal 4.7. I know it's old and lame and long time ago deprecated but I really need it for a project I'm currently involved in.
I've tried to search it but without any luck.

Thanks,
Alex


texts:
How do I install the Field Redirection module?

I want to display a photo on the front page that redirects to another page. I have Md Foto theme and would like the photos on the front page to click through to a basic text content, a different node.


texts:
I have a bunch of events that users should be allowed to register to. But I am trying to use one basic form that asks for the following fields:

First Name
Last Name
Phone Number
Email
Gender

I was wondering if there is a way to connect that form to a specific event. Is it possible to have a submissions field that is hidden from the user that auto populates with the node ID or something similar to that approach?

Any help would be much appreciated! Thank you!


texts: setContainer Error When Registering an EventSubscriber Service

texts:
I am trying to create a basic event subscriber, but when I add the services.yml file and attempt to rebuild the cache with drush cr, I get this error.

  In Drupal.php line 130:

  \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

If I clear the cache from Drupal, it works fine, but Drush always errors out. If I remove the services file, Drush works fine again.

Has anyone seen this before? I don't want to move forward without resolving this. I have added services and event subscribers in this project before without an issue. I double checked spacing structure, etc.

module/gary_custom.services.yml

services:
  gary_custom.custom_event_subscriber:
    class: Drupal\gary_custom\EventSubscriber\CustomEventSubscriber
    tags:
      - { name: event_subscriber }

module/src/EventSubscriber/CustomEventSubscriber.php

namespace Drupal\gary_custom\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CustomEventSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    \Drupal::logger('debug')->debug('get sub events');

    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

  /**
   * This method is called whenever the KernelEvents::REQUEST event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function checkForRedirection(GetResponseEvent $event) {
    \Drupal::logger('debug')->debug('hitting');
  }
}

I am using Drush 9.4.0.


texts: How to add pagination in a block created from a custom module?

texts:
I have made a very simple block that displays an array of strings as a list. I am achieving this by implementing hook_block_view() in my .module file. Right now the list displays ok, but I would like to paginate it so that only a few list items show at a time.

I am not getting the list from a database, I just have an array of strings as I mentioned before. I have been looking at theme_pager functions, but I am not sure how to use them to do what I need. Any help or examples would be greatly appreciated! Thanks!

Edit:
I have found the following code here (Adding Pagination to to custom form block results) and I am having trouble making sense of this part of it:

function latest_news() {
     $query = db_select('node', 'node');
     $query = $query->fields('node', array('nid'))
            ->condition('node.status', 1) //Published.
            ->condition('node.type', 'auction_news');
     $query = $query->extend('PagerDefault');
     $result = $query->limit(20)->orderBy('node.created','DESC')>execute()>fetchAll(PDO::FETCH_ASSOC);
     $paging = theme('pager');
     return theme('latest_news',array('data' => $result,'paging'=>$paging));
}

Could someone please explain how this part could be modified to use a simple list of strings instead of a database query? Thank you very much in advance!


texts: I need to create a SOAP web service that gets user-related information, but I want to secure the service with two-way ssl certificates (mutual authentication). I have created a module that does the Drupal user work, and I can access it by mapping a url to the function as usual, but I was wondering what is the best way to create a webservice in Drupal with mutual SSL authentication? Should I use Drupal modules/framework or just roll my own web service using SOAP calls? How do I expose this? I need to authenticate both the client and the web service, as both will be sending sensitive information.


texts: Is it safe to delete 'sites/modules.sav'?

texts:
After the upgrade to the newest Drupal v7.31 I've found a new directory called sites/modules.sav with some subdirectories like

entity
entityreference
securelogin
securepages
session443

What is the purpose of this directory?

Can I safely delete this entire directory 'modules.sav' after the successful upgrade?


texts: ImageCache action: How do I set the width as 500px and the height will constrain propotion to width?

texts:
I use ImageCache Action to add watermark and resize image.

How do I set the width as 500px and the height will constrain propotion to width?


texts: How do I hide Bartik Main Menu on front page from unauthenticated users?

texts: I have a private website in which content can only be viewed by authenticated users.  All I want is the login box for non authenticated users.  I am using NodeAccess and also Rules module to do this.  Seems to work fine with one exception.  The pages which should only be visible after login show their links to the anonymous user on the Bartik theme main menu right on the home page.  All menu items appear including those for pages specifically limited to administrator viewing.  True, clicking on them merely brings up the login dialog box so the individual can't see the page, however, I don't want the menu itself to appear at all until the person is authenticated. How do I make the entire menu disappear if unautenticated? Thanks in advance.


texts: Conditional fields for the field type 'managed_file' is not working in Drupal 8

texts:
I have two radio buttons

Enter The Text
Upload a Text File

If user select the 1st option, a field of type 'textfield' will appear & if they select the 2nd option, a field of type 'managed_file' will appear.
 But this code with working fine for textfield but not working for managed_file
 Now, how to implement conditional fields in Drupal 8 ?

This is my D8 code.

    $form['field_type'] = array(
    '#type'    => 'radios',
    '#options' => array_combine( array(t('Enter The Text'), t('Upload a Text File'))
                                 array(t('Enter The Text'), t('Upload a Text File'))
                                ),
    '#title'   => t('Choose entry type.')
  );

  $form['imgurl'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Enter the text'),
    '#states'        => array(
      'visible'      => array(
        ':input[name="field_type"]' => array('value' => t('Enter The Text')),
      ),
    ),
  );

  $form['file'] = array(
    '#title'              => t('Choose Text File'),
    '#type'               => 'managed_file',
    '#progress_indicator' => 'throbber',
    '#progress_message'   => NULL,
    '#upload_location'    => 'public://files/',
    '#states'             => array(
      'visible'           => array(
        ':input[name="field_type"]' => array('value' => t('Upload a Text File')),
      ),
    ),
  );


texts: Error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given

texts:
I'm using Entityform with some custom module for multipage which is based on FGAM.

Recoverable fatal error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given, called in includes/form.inc on line 1200 and defined in drupal_array_get_nested_value() (line 6771 of includes/common.inc).
The website encountered an unexpected error. Please try again later.

Why this happens and how do I fix or debug this kind of error?


texts:
I used simple XML sitemap module to create a sitemap for search engines but now I need one sitemap for visitors.
Can I create this manually instead of using a module because the site already has too many modules?
I was thinking to create a basic page and just add the links there one by one.
Is this a good way?


texts:
I changed error logging so that errors are being written to /var/log/drupal.log, switching from using Drupal's dlog to syslog, following these instructions, in order to reduce resources used to write them to the Drupal database. All is well with that but when I tail the log file, it's reporting all the page not founds, login attempts and other annoying information that I don't want. How can I configure the .log so that it is limiting what is being written to it, or so that it writes different types of messages to a different .log. For example, can I config the log to ignore "page not found" warnings, but put "access denied" and "php" warnings in different respective logs?

Debian uses rsyslog and I needed to enable syslog module in the CMS and edit the .conf (in /etc/rsyslog.conf) to include a line that was needed for the CMS to interact with it.

Now, if I had more than one domain, I could use the following code to separate logs for each domain. Can I use something similar to separate types of messages instead?

if $programname == 'drupal_www_example_com' then /var/log/drupal/drupal_www_example_com.log
& ~

local0.* /var/log/drupal/others.log
& ~

How do I find out the name of the string I should use instead of $programname? It's probably $type. I'm thinking something like this would be added to the rsyslog.conf:

if $[type_of_message] == 'name_of_type_of_message' then /var/log/drupal/drupal_access_denied.log
& ~

local0.* /var/log/drupal/drupal.log
& ~

Also, the problem with the above idea is that it chooses one thing and logs the rest to drupal.log; I'm not sure on the syntax to create the "or if" statement to give it more instructions.

Note: local0.* is the syslog facility I defined in the CMS. I am not sure if this belongs in the Drupal community or if I should post to stackoverflow.

Edit: for now, I'm fine with running tail /var/log/drupal.log | grep php to filter messages by type "PHP", etc. I am a little concerned about how large the log is though.


texts: How to add an existing field to an user account?

texts:
I created a vocabulary in Structure>Taxonomy>Add Vocabulary. Then I add terms to it.

My Vocabulary fields look like this :

I want to display this vocabulary into accounts fields, I want to add existing fields but I can't find the term reference.


texts:
I'm attempting to allow the user to dynamically choose a number of fields based on a dropdown box using an ajax call, but I can't seem to get the ajax call to rebuild the form afterwards.

<?php
class AJAXexample extends BlockBase {
    public function blockForm($form, FormStateInterface $form_state) {
        if (empty($form_state->getValue('number'))) {
            $form_state->setValue('number', 3);
        }
        $form['columnNum'] = [
            '#title'   => t('Number of Columns'),
            '#type'    => 'select',
            '#options' => [
                1         => '1',
                2         => '2',
                3         => '3',
                4         => '4',
            ],
            '#default_value' => $this->configuration['columnNum'],
            '#empty_option'  => t('-select-'),
            '#ajax'          => [
                'callback'      => [$this, 'columnCallback'],
            ],
        ];
        for ($i = 0; $i < $form_state->getValue('number'); $i += 1) {
            $form['column'][$i] = [
                $i => [
                    '#type'       => 'details',
                    '#title'      => t('Column '.$numTitle),
                    '#open'       => FALSE,
                    'columnTitle' => [
                        '#type'      => 'textfield',
                        '#title'     => t('Column Title'),
                        '#value'     => $config[0]['columnTitle'],
                    ],
                ],
            ];
        return $form;
    }

    public function columnCallback(array &$form, FormStateInterface $form_state) {
        $form_state->setValue('number', 10);
        $form_state->setRebuild(true);
        return $form;
    }
}

The number of textfields is based on the form_state variable 'number'. The callback columnCallback changes the form_state variable to 10, and is fired when the 'columnNum' form field is changed. However the form isn't rebuilt with the new number of fields even though $form_state->setRebuild(); is called. Is there a way to get the form to rebuild after an ajax call?

NOTE: I have already tried techniques such as replacing or appending the items of the form inside of the actual ajax call but when that happens none of the input into the replaced fields get passed to $form_state.

UPDATE:
After attempting 4k4's solution I receive an error

Recoverable fatal error: Argument 1 passed to Drupal\Core\Render\MainContent\AjaxRenderer::renderResponse() must be of the type array, null given, called in /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php on line 89 and defined in Drupal\Core\Render\MainContent\AjaxRenderer->renderResponse() (line 45 of /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Render/MainContent/AjaxRenderer.php).

The belief is that the error occurs because $form['column'] is returning null despite being created as a container in the blockForm function. I've attempted calling the callback in other ways like

'#ajax' => [
    'callback' => '::columnCallback',
]

and

'#ajax' => [
    'callback' => [$this, '\Drupal\my_examples\Plugin\Block\AJAXexample::columnCallback'],
]

But I receive the same error. Curiously, when I change the callback to return the entire $form instead of just $form['column'] it repeats the form (a copy of the form appears below the current form) and still without the proper number of columns.


texts: Why are methods for going from the MenuLinkContent menu link plugin class to the MenuLinkContent entity protected?

texts:
Loading a menu tree and parsing the menu_tree_elements loading the menu_link_content entities is not straight forward. I have to perform it like this.

    $menu_id = 'menu';
    $menu_tree = \Drupal::menuTree();
    $menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_id);
    $menu_tree_elements = $menu_tree->load($menu_id, $menu_parameters);

    foreach($menu_tree_elements as $menu_tree_element){
        $id = $menu_tree_element->link->getMetaData()['entity_id'];
        $menulink = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($id);
    var_dump('Title: '. $menulink->label());
    }

I notice that getEntity() is a method that does almost exactly what I'm already doing in order to get the menu_link_content, but it's a protected function. Why would they make that function protected? Is it because I'm doing things in a really round about way when I should be using a different method?


texts:
i've been learning Drupal 7 using Acquia DevDesktop and i have several sandbox type website running on my laptop but now i'm trying to access the databases from the command line. but in the settings.php almost the only that's not comment out are at the bottom, where it makes reference to inc.'s like this.

if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) &&
file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .          '/loc_rmywebsite_local.inc'))
  require($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] .     '/loc_mywebsite_local.inc');

but then when i do a search for these inc files locally on my laptop, nothing comes up, as if they don't exist. so
One, where are these files?
and two, find where the DB settings are for these local sites so i can start learning how use the command line, or maybe Drush.

yes, i should probably have written down these setting but didn't.


texts: How to programmatically populate a country field

texts:
We are using the Countries module to provide country fields where editors can choose a country and it gets displayed in the frontend. Which works absolutely fine.

But we want to fill that field programmatically through a custom module. No matter what value we provide to fill the field (country name, ISO 2 code etc.) the field doesn't get populated.

We are certainly sure that there is no any error somewhere else as we are filling multiple fields in our module and all are working as expected.

We want to know in which format does the country field expect the value to be?

Clarification:

We have a field field_country in profile2 with the Country type coming through Countries module.  We are getting input in our module through following code in our form:

include_once DRUPAL_ROOT . '/includes/iso.inc';
include_once DRUPAL_ROOT . '/includes/locale.inc';

$form['country'] = array(
  '#title' => t('Country'),
  '#type' => 'select',
  '#description' => t('Please Select Your Country Where Do You Belong To.'),
  '#required' => 'true',
  '#options' => array('' => t('-Select a Country-')) + country_get_list(),
  '#default_value' => isset($values['country']) ? $values['country'] : '',
);

We have also tried '#type' => 'country' and a few other things but same result.

For submitting this value we are using the code:

$profile->field_country['LANGUAGE_NONE'][0]['value'] = $data;


texts: I'm working on integration of my D7 module with Rules. I have custom SQL table with 2 columns node_id and status. Status may have values 0, 1, 2, 3. How can I create event with hook_rules_event_info to react on status change? I.e. status changed from 0 to 1 -> send email to node owner.


texts: How can I add alphanumeric, numeric and email validate validation in my custom form?

texts:
function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['empemail'] = array(
  '#weight' => '2',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('Employee Email'),
);
$form['empdesignation'] = array(
  '#weight' => '3',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Designation'),
);
$form['mobile'] = array(
  '#weight' => '4',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('Mobile No.'),
);
$form['ipphone'] = array(
  '#weight' => '5',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('IP Phone'),
);
$form['qualifications'] = array(
  '#weight' => '6',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('Qualifications'),
);
$form['profile'] = array(
  '#weight' => '7',
  '#required' => '0',
  '#type' => 'textarea',
  '#title' => t('Profile'),
);
$form['file'] = array(
  '#weight' => '8',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
$form['captcha'] = array(
  '#weight' => '9',
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);
 $form['submit'] = array(
     '#weight' => '10',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('<pre>'.print_r($form_state['values'],1).'</pre>');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

i want to add advance level validations so that no one enter special characters to these form fields. Currently required is working.


texts: What is the correct way to create a new ImageItem and attach it to a FileFieldItemList?

texts:
I'm writing a custom module to pull in some images from an old D6 installation (the cck plugin is failing to connect images to the correct node). So I need to be able to create new ImageItem and add them to the field.

Can I simply create a new object like:

$field = $node->field_gallery;
$img = new ImageItem();
$img->setValue(array(
   "target_id" => 123,
    "alt" => "Alt text"
   "title" => "Title text"
));

$field->set($delta, $img);
$node->save();

Or do I need to do something with entityManager to get it linked properly?


texts: I have using Commerce Kickstart and Commerce Marketplace. I have added 2 products into the cart (products from different stores).The problem is when I taken review order page it shows as different order, also different order created. What is wrong with me.I wish to add these two product as the same order.


texts: How to change the theme for a particular admin page in drupal?

texts: I have a page with url ?q=admin/settings/history . Is there any way by which I can change the template for this page alone. I tried using hook_preprocess_page but I was unable to change the layout of page. Could someone please lead me in the right direction?


texts: Get the total value of the users vote in Rate module

texts: I  have added rate module to enable voting on comments and content. But I want to get the total no. of vote got by a users comment and give badges based on that. I have no clue how to do it.


texts: Filter commerce orders by the user that updates there state

texts:
If a user updates the state of several orders to completed.

I want to then use views to filter all orders that had there state marked completed by that user.

Is this possible i have tried but failed?

I would also like to filter by the order state updated date.


texts:
I want to disable the front-end access of my headless Drupal site, that is just a REST API for a Vue site.

Except for the login page, there is no need to access any node, taxonomy or view directly as everything is delivered via REST.

How can I achieve this?


texts:
I have a field in a content type that is a list_text with a key/value pair where the key is stored in the database and the value is the text visible in the drop down menu.

I imported a large amount of data.  When I look at the data in a view or view a node, the key shows up.  However, after I edit the node, whether I've made changes or not, the value starts appearing in the view and in the node.  I would like this to be the case for every node, but can't possibly go though and manually edit each node.

Can anyone tell me where in the database the info that tells Drupal to use the translate the key to its value is stored?


texts: How to redirect after submitting a multi-step registration form?

texts:
I want to redirect after submitting  multi-step registration (Two step registration), and also I want to prevent the automatic logging to drupal website after registration completes.

I tried the normal way

$form_state['redirect'] = 'url';

But it doesn't work.

Then I checked the form action, it also goes to the specified URL after completing the first step.

I just put some of the codes in my module here

function caubo_registration_form_alter(&$form, &$form_state, $form_id) {
if ($form_id != "user_register") return;

// custom codes
.....

if (isset($form_state['storage']['page']) && $form_state['storage']['page'] == 2) {
caubo_register_page_two($form, $form_state);
return;
}

if (isset($form_state['storage']['page']) && $form_state['storage']['page'] == 3) {
caubo_register_page_three($form, $form_state);
return;
}
}

I tried the Rules Module and implement the method here, but after completes the registration form, the user is automatically logged in to drupal website, how prevent it?


texts: Editing order confirmation email in Drupal 7 Commerce

texts:
I am using Drupal 7 with Drupal Commerce (not Kickstart). I am having difficulties editing the order confirmation email. I am hoping to basically "duplicate" the Order review page from the Checkout process to be included in the email (order items, prices, total and billing info).

The module I installed is Commerce message and I just had no luck trying to edit the order confirmation email. I do have the Tokens module installed and enabled.

I tried to edit the email under Structure -> Message Types, however, the replacement tokens available (for example: [message:message-commerce-line-item]), don't seem to output anything in the email. Actually, the token itself is included in the email, like so:

[message:message-commerce-line-item]

I have tried several other tokens with the same result. I tried to select Filtered HTML and Full HTML.

Reading through the Drupal Answers I also tried to use !order-summary token, which seems to work, however the email is "unstyled" and includes HTML tags, like so:

     testing credit card payment

     $0.25

     1

     $0.25

What puzzles me the most is seeing answers like this or this, stating that

  You want the Commerce Message module and it's dependencies. It includes customer emails with a full order details, including customer profiles and all the products purchased

Any ideas on the issue? I failed to find any Commerce message tutorial or the way tokens should be used with it in Drupal Commerce. I'd be happy to go through one if it exists, I would be willing to even write one for future users who might have the same problems once I figure this out.

Thanks


texts: Views Term ID (with depth) greater than specific depth value

texts:
I'ved used Taxonomy Views Integrator to take over my taxonomy terms pages.

I'd like to have the main view only show items beneath the term in the hierarchy and a views attachment (above) that shows the items directly at that level of the hierarchy.

So far this works perfectly except that "Term ID (with depth)" only care how far to look rather than where to start. I'd like the depth to be greater than 1.

Is this possible with another approach perhaps?
I don't understand what "Term ID depth modifier" does at all, maybe that's the key?
Maybe I need a relationship to accomplish this?

Views offers the concept of exclusion when taking arguments, but that only works for node IDs. Is there a way to extend this?

Looks like I might be stuck using Views Exclude Previous because the exclude option is missing from Drupal-6 Views-2.x.

SEE: http://drupal.org/node/733686

From that thread it seems to work in Drupal-7 Views-3.x, but not for me :(


texts: How to make custom entity type revisionable with existing content?

texts:
I'm trying to make a custom entity (with existing data!) revisionable, but I run into multiple very serious issues including schema update errors, difficulties with creating revision data for existing content, and so on...

Has anyone done something similar successfully? Is there a fairly simple way to do it?


texts:
I'm investigating how to create a scalable drupal system where nodes can be shared across different sites. In order to support future growth, it is likely we will need to "plug in" more servers/sites into the network.

I was thinking that this would be best achieved with a central site for storing the master records, users, and permissions, and then the slave sites would hold copies of these where relevant. Not all sites will need all the nodes, only those that are linked.

Alternatively, the central site could store which site has the master record. That might make it easier to grow. Thinking of node id's, the end solution needs to cater for the fact that these numbers could easily hit the millions.

It may be a crazy idea and maybe Drupal is not the right platform for this too.

Any ideas?

UPDATE: The concept is similar to that of sharding and map reduce (my basic understanding that it), yet my biggest concern are the node id's. If the system hits the number of users/groups/nodes we are looking at, we could hit the nid int limit and experience performance issues well before that point too. So a distributed model seems to be the best direction.


texts: Architectural - How to setup content types for very unique editable pages

texts:
We are working on a site for a client. This page has in total about 30 different pages. Each page has a unique and complicated design. In order to give the client the possibility to edit texts on the pages without changing the design we created text fields for each content type. Each content type has around 30 fields (text or long text) which we manually render in the template files. Each field has a unique machine name. We always created a new field whenever we needed a new field in one of the content types. And each content type has only a few contents (variation of the page).

Current structure:

Content type 01
    Field 01
    Field 02
    ...
Content type 02
    Field 05
    Field 06
    ...

The question now is if there is a better way of building such a architecture, since we are having a quite large php memory usage. The idea of drupal is to create a content type and have then a lot of contents of that type. But that approach doesn't fit to our customized page design.

One possible solution which we gathered is to reuse the fields in all the content types. Originally we named the fields in the example above field_content_type_01_field_01 and field_content_type_02_field_05. This solution would mean we have to change the fields to have field_field_01 and reuse that field in all content types.

But is there a better way for our setup?


texts: How to build a user authentication workflow with AngularJS using RESTful module?

texts:
I'm building a single page app with AngularJS and Drupal as the backend. I'm using the RESTful module. However, I do not have much to go on to build a user authentication workflow.

There are several techniques to authenticate users with a SPA. For example, storing session information in a cookie or in a token. In order to keep a persistent authentication with a token, AngularJS stores the token in local storage. I've been reading that this causes security risks because other scripts are able to access local storage.

Also, RESTful comes with a token authentication module which stores tokens on the server.

The first question is which form of persistent authentication to use? Do I have to completely make the SPA headless Drupal? If the app is headless, using token authentication, do I have to completely remove all the out of box user authentication workflow, for example, resetting a user's password, from the app? Is there a hybrid solution? If the information is being consumed and altered by mobile apps and other non standard means, is using cookie authentication out of the question? If that is the case, on a desktop app, how do I prevent users from accessing user URIs? Basically, I have no clue what is going on and there isn't much information about secure solutions.


texts: print theme_get_setting in php-as-css file

texts:
I'm trying to print out settings from my theme's theme-settings.php into a file called custom.php. Below is the code I'm using in custom.php:

<?php
    header("Content-type: text/css; charset: UTF-8");
define('DRUPAL_ROOT', '/path/to/my/drupal/installation');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

body {
    background: url(<?php print (theme_get_setting('theme_custom_background_path')) ?>);
?>;

This is what the result is when the page is rendered in the browser:

body {
    background: url();
}

I'm obviously missing something here -- theme_get_setting isn't working. I'm not sure what kind of code I need to link this file to my theme.

Does anyone know if there is a way to get custom.php to recognize the settings I've defined in my theme's theme-settings.php file with theme_get_setting? I feel like I'm so close but just missing a few lines of code.

At the end of the day if I absolutely need to, I can just print the settings out inline within the head section of html.tpl.php - but I'd much rather include them in a separate stylesheet with the .php extension.

Any suggestions?


texts: I'm using the Omega theme and have a zone that I need a div around for a certain content type. Trying to figure out the best way to do it. Was thinking a preprocess, but no clue which. Fairly new to Drupal so bare with me.


texts: How to add an 'operations' link to a custom route?

texts:
I'm implementing a custom entity with bundles in Drupal 8.

In the list of bundle entities page (i.e. equivalent to Node's Content Types listing page), I would like to provide an extra option to the list of operations, which currently include Edit, Manage Fields, Manage Display, Delete, to let the user create an entity of that bundle. So if this were on Nodes, then it would be like adding an "Add Content" link for each content type in the content listing page, which would take you to /node/add/{node_type}.

Relevant code I have so far:

Added an 'add-entity' option in the links section of the config entity's annotations:

* @ConfigEntityType(
*   id = "bloom_stem_type",
*   label = @Translation("BloomStemType"),
*   bundle_of = "bloom_stem",
*   ...
*   links = {
*     "edit-form" = "entity.bloom_stem_type.edit_form",
*     "delete-form" = "entity.bloom_stem_type.delete_form",
*     "collection" = "entity.bloom_stem_type.collection",
*     "add-entity" = "entity.bloom_stem.add_form"
*   }
* )
*/

Note that this points to a route in another entity, the actual entity that this is a bundle for.

That route is defined in (routing.yml):

entity.bloom_stem.add_form:
  path: '/admin/bloom_stem/{bloom_stem_type}/add'
  defaults:
    _title: 'Add BloomStem'
    _controller: '\Drupal\bloom\Controller\BloomStemController::addForm'
  requirements:
    _entity_create_access: 'bloom_stem'

Then I've implemented getDefaultOperations on a custom list builder class:

class BloomStemTypeListBuilder extends ConfigEntityListBuilder {
  ...
  /**
   * Gets this list's default operations.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity the operations are for.
   *
   * @return array
   *   The array structure is identical to the return value of
   *   self::getOperations().
   */
  public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);

    $operations['add'] = array(
      'title' => $this->t('Add'),
      'weight' => 10,
      'url' => $entity->urlInfo('add-entity'),
    );

    return $operations;
  }

However, when I visit the entity bundles list page, there's an exception thrown about being unable to create a route/path. On step-through debugging this seems to be because Entity::urlInfo() does not appear to use the route set in the annotation, thanks to this line that constructs its own route:

$route_name = "entity.{$this->entityTypeId}." . str_replace(array('-', 'drupal:'), array('_', ''), $rel);

The only documentation I could find on the links part of the annotation just
says:

  links
  Entity URL definitions, referencing to routes from MODULE.routing.yml.
  'canonical' is the default route for the entity. edit-form and delete-form
  can also be set. These are mostly used for Field UI. Arbitrary keys can set
  here. For example, User sets cancel-form, while Node uses delete-form.

Which I took to mean ("referencing to routes from MODULE.routing.yml") that if I
referenced a route, that route would be used.

Aside: Other things I've tried include creating the URL more directly (clearly not the
right way of doing things):

$url = \Drupal::getContainer()->get('url_generator')
  ->generateFromRoute('entity.bloom_stem.add_form', ['bloom_stem_type'=>$entity->id()]);

That generates a valid path, but a string value is not what getOperations
is expected to spit out under its url key output.

Can anyone fill me in on how this is supposed to work/where I've gone wrong?
Thanks.


texts: Display field collection items by using twig

texts:
I'm using the field collection module in Drupal 8 to encapsulate event informations so I've got a field collection with six sub fields (place, starting time, etc.).

In my twig template field--field-event.html.twig, I'd like to extract each item of the field collection and bring it separately to the view - but I can't figure it out. What's the right way to get the content of each field collection item and process it individually?

{% for item in items %}
  {{ kint(item) }}
{% endfor %}

Iterating through the field collection with above code gives me an impression that the field collection items have got a content (with #markup) and attributes but how do I get to the core/values of the field items?


texts: Create custom template for a specific node without node ID?

texts: I want to create a custom tpl for a specific node. However I dont want to use node id in the file name (page--node--11.tpl.php). Is there any way to do it?


texts:
I have got content types called 'Online Discussion', henceforth referred to as OD and a content type called 'Online Discussion Reply', henceforth referred to as ODR. Having Entity References (drupal.org/project/entityreference) to eachother.

When one ODR is created (via a front end custom form) it references its "parent" (the OD whose page it was created) and via Corresponding Entity References (drupal.org/project/cer) same thing happens the other way around.

In an OD's page, via theming, a specific amount of referenced ODRs are shown, the 10 latest. They are presented as rendered entities without any View's  or Panel's involvement at the moment but I am open to changing that if necessary.

Each ODR has its own instance of the reply form, enhanced with quoting functionality.

Also, the ODRs can accept comments from specific roles, via a custom front-end form as well.

The requirements:

1) I need some way to load previous (all or in batches) replies with AJAX. Currently I am firing a jQuery ajax callback to a view page that fetches the previous ODRs accordingly and I inject their HTML into the DOM. That works, but in a test-case scenario with over 200 nodes referenced, that seems to take some time

2)I need a way in which after a fixed time interval to look for new ODRs and append them giving the OD a 'livelike' behavior. At the moment I do this in the same way, and it seems to work pretty ok.

3) I need some efficient way to apply Drupal Behaviors to the new elements that come to the site so they have their contextual links functional etc. I've done that using Drupal.attachBehaviors(context); but there are issues.

The issues so far:

I. Multiple instances of the same form on the same page.
Although Drupal handles drupal_html_id() on the initial OD page load, the way I use AJAX breaks the ID uniqueness. If for example I have 10 forms in my initial load, and I bring 2 more via AJAX, IDs for the first 2 will be repeated since I grab the HTML the view generated as a whole.

II. Performance issues in a 'Load all previous ODRs' case. Pretty self explanatory. Pulling 200+ entities and injecting their HTML is pretty heavy lifting.

III. Drupal.attachBehaviors - when using AJAX like the way I described, the HTML for the contextual link is produced just fine. Problem occurs with the javascript involved into it. So after some hours of researching, since there is very little documentation on this, I stumbled upon Drupal Behaviors which pretty much solved that issue, but gave me a new set of problems to deal with:

onLoad events, now in a behavior, run each time an AJAX event is fired causing multiple event binding (unbind before bind solution at the moment)
some onLoad events, like the collapse of the textareas the multiple forms use, cause usability issues. For example, you are typing a reply or comment, a new ODR comes into the site via the recurring ajax call and collapses your textarea.
pretty messy and incrementally difficult to manage code to make sure I handle all the possibilities via jQuery

So, finally, the question:

What are the best practices in a Drupal context with which to achieve the desired described result?


texts: View to display the comments of the curent user nodes

texts:
Please how to create a simple view to display the comments of the curent user nodes, only comments,
Thank you.


texts: Using "if statements" to add classes in Twig

texts:
I'm attempting to use an if statement to determine the value of a field and print a class based on that value. I'm not getting any errors, but the addClass is not working. No classes are being added. I'm assuming it's a simple syntax error. I'm a designer first, and I'm new to Twig templating. Thank you in advance!

{% for key, item in content.field_stat_value if key|first != '#' %}

0

{{ content.field_stat_title[key] }}

{{content.field_special_character[key]}}

  {% endfor %}


texts: Conditionally Hiding / Stopping a view from display

texts:
I have two views, for taxonomy pages, one displays the products of the current term (using contextual filter "Content:has taxonomy term"), and other display the sub-categories of the term (using contextual filter "Taxonomy term: Parent term").

My problem is that I want to display product view only when I does not get any result in sub-category view.


texts: I'm really stuck displaying content type's computed field in view. Computed field value calculated properly and stored in database (value is a generated HTML code), but in view I get HTML just printed out as text. Looking through the page source code I found that HTML tags are encoded and looks like that &lt;a href=&quot;LINK_HERE&quot;&gt; So I'm wondering how to display custom field's HTML in view (seems to me that was a some custom module for this purpose?)?


texts: Avoid creating menu items for every node

texts:
I have defined a content type and unchecked every menu item under Menu settings -> Available menu. The problem is that every time i add a new node for the content type, Drupal creates a new menu item in the primary menu.
How can i avoid it?


texts:
I'm trying to create a comic reader like a flip book. I think the views module can do this but I don't know how to do it.
I plan to structure like this:

Terms (Series)
     - Sub Term (Chapters)
           - Nodes using image field (Pictures)

What I want to do is I want make a views in the subterms to show only one node at a time but the node contains the image that is linked to the next node in sequence order. So how can I do this? I only want the nodes from the subterm to show up


texts: How to determine if a translatable field has translation enabled?

texts:
How can I figure out if a translation for a translatable field has been enabled?

I don't mean if a field is translatable in general. e.g.:

$entity_type = $entity->getEntityTypeId();
$bundle = $entity->bundle();
$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);
foreach($fields as $field){
  if($field->isTranslatable()){
    // Do something.
  }
}

Could the langcode be a reliable information? If it is 'und' e.g.:

if($entity->get('name')->getLangcode() != 'und'){
  // The field translation is enabled:
}


texts: Rule to send an e-mail with the URL of an uploaded attachment after node change

texts:
I have a Drupal 7 site with a custom node type with a custom attachment field. After a (kind of this custom) node has been published, I got an e-mail with the help of Rules module. I would like to set up an another rule, which sends me an another e-mail, when somebody edits this node and uploads an attachment. Inside the mail, I want to see the full url to the uploaded file.

After a several test, I'm not able to insert the full path to the uploaded file. The [node:field-attachment:file] doesn't work at all. I'm able to insert (manually) the url where this file resides, but after I can not insert the file name (so even the filename would be enough for me).

So with the [node:field-attachment:file] I got an error: *Fatal error: Call to a member function value() on a non-object in /home/xxx/sites/all/modules/entity/entity_token.tokens.inc on line 297.*

Which is exactly this:

/**
 * Gets the token replacement by correctly obeying the options.
 */
function _entity_token_get_token($wrapper, $options) {

   if ($wrapper->value() === NULL) {
// Do not provide a replacement if there is no value.
return NULL;
}

With the [node:field-attachment], I'm getting the e-mail, but it contains this: You can download the file from here: Property 0

Which token should I use to get the url (or the filename) of the actually uploaded file when I edit the node?


texts: Adding 'lang' attribute to language links in template.php

texts: I am not a Drupal developer, but still I would like to know how to make the links in a language switcher HTML5 valid. It seems these links lack an attribute 'lang' (with as value the abbrevation of the language). How would I do that in template.php?


texts: How do I create an invoice without product?

texts:
Am working a project that required generating invoice for customer service payment, 'rent' to be specific. Am still a newbie to drupal environment (I do Wordpress Stuff).

Since the Payment is going to be recurrent I choose Drupal Commerce, but am confuse as to how to configure the module(s) needed.

Features that I need
- Admin created invoice for Client (registered user) with invoice status UNPAID
- Invoice sent to Client via email (PDF format)
- Client Pay at Bank and upload Prove of payment
- Admin change the invoice status to PAID upon Validation.

I could Create Content type for the invoice, but I may not be able to create PDF and mail it to user in which Drupal Commerce would handled well with other Contributed Module.

I should be able to handle it if I can get a kind of guide.


texts: How to change the node breadcrum name & there url inside in drupal 7?

texts:
There is a node where breadcrum shows like this :

Home › Shop Products › Product Name

Now I want to change the breadcrum. I can easily change the "Product Name" but unable to change the "Shop Products" name. How can I change. I have try to add custom code in template.php file but unable to got result.

Please help me to solve this.


texts: Views Summarize Won't Sum when field is output as link (D7)

texts:
I'm using Views Summarize module for one of my views. I need to output the field as link and sum them up, but the total is displayed as $0.
When I uncheck the output the field as link option, the total is displayed correctly.

http://i.stack.imgur.com/SNK0h.png

Anyone has a solution for this?


texts: How do I name the comment.tpl.php file to use it in my own theme?

texts:
I have copied comment.tpl.php from mytheme/modules/comment into
root/sites/all/themes/mytheme/templates. What should I name it to override the core template?

The form ID is places-to-go-entry. I tried comment--places-to-go-entry.tpl.php, but it didn't work.
The content type is places_to_go_entry. I tried both comment-form--node-[content-type].tpl.php and comment-form--node-[places_to_go_entry].tpl.php, but it didn't work.

I am looking to hide the subject area in comments and Add new comments, and modify Permalink Submitted by Joe Smith on Sat, 03/30/2019 - 19:29
to be by Joe Smith 03/30/2019.

Using template.php, I successfully hide the New comment subject label and dialog box, so I thought I'd go this route. I don't know what variables to work with to hide the subject area in the comments list, and I don't know know what variables modify for the permalink line.


texts:
Good day

I only have access to my Drupal site's admin panel, not the ftp server.
Now how can I upload a jQuery plugin, for example an image slider (with the js and css files) onto the site using the admin panel?
Note that the plugin is not part of the theme.

As I understand you need to add it on your theme's .info file:

scripts[] = js/my_jquery_plugin.js

BUT, is that file only accessible via ftp?

How can I do this using the admin panel?

Thank You


texts: How do I set the options for a programatically created content type?

texts:
For example, if I want to set 'Publishing options - Promoted to front page' to 0 in a .install file when creating a new content type.

I've looked in the variable table, where I was expecting to see variables for these options, but it's not obvious to me. What am I supposed to set?

Thanks.


texts: Composer require takes very long to download modules

texts:
I am seeing that it takes a very long time to download a module via composer. For example I just tried to require the Stage File Proxy Module on a brand new Drupal project created from Drupal Project Template and it took around 9 minutes.

 2016-07-08 22:31:53 ☆  Alberts-MacBook-Pro in ~/www/d8
± |master ✓| → composer require drupal/stage_file_proxy:8.*
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/6:  http://packagist.org/p/provider-2015-10$4808a9ff7f19ac4170168746ed24f8694f9e5a0799c355e26375ce90725a8828.json
    2/6:  http://packagist.org/p/provider-latest$4cfacf88e4e332a9850bd06a12ceeedf743ffac37097fdb03d8a8b6d08a0b0da.json
    3/6:  http://packagist.org/p/provider-2015$f56365502d2bdac013de2da3ae50e3df33103e9c86fd7092fe072d0e4cfc0efd.json
    4/6:  http://packagist.org/p/provider-2014$dadae06a2b0889e9967e732c6861aae8f5c4df363fdb3829bea92e2b76acbd38.json
    5/6:  http://packagist.org/p/provider-2016-04$b2962d9a234c8a0c67c152f6a5197b3a4e41ce384da5bb0c9cc7404d31e7ebe9.json
    6/6:  http://packagist.org/p/provider-2016-01$c7705812f13e96daf6bc63fbb870fda9e082bf53e3b49fcdee5088002aa8d5a7.json
    Finished: success: 6, skipped: 0, failure: 0, total: 6
  - Installing drupal/stage_file_proxy (8.1.0-alpha1)
    Loading from cache

Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

 2016-07-08 22:40:45 ☆  Alberts-MacBook-Pro in ~/www/d8

I have seen coworkers have this same issue so it definitely isn't my machine.

I do have Prestissimo installed.

Is everyone else seeing this same slowness?

Update

Ran composer clear-cache and reran with -vvv: http://pastebin.com/6xTYB0sd. This time it took 7 minutes.

Ran composer clear-cache and reran with --prefer-dist -vvv: http://pastebin.com/g6BtTMzy  This took around 5 minutes.


texts: How to display parent Taxonomy ID in REST export

texts:
I want to configure REST export View in which I display taxonomy term name, id and parent ID. How to insert parent taxonomy term id, why it's not available in FIELDS?

Here is current REST export settings, I only missing parent term ID.


texts:
I just pasted a google analytics snipped into my template. When I preview the view source for the page, the script snipped is displaying all in one line.

How do I get it to display as it does in the page.tpl.php file?

I am using netbeans.


texts: How the RTL css system works in drupal specially in omega theme?

texts:
I am building a multilingual site (using Omega theme) which has two languages, one LTR and the other is RTL.

Can someone please explain how the RTL mechanism works for css in Omega theme?


texts: Creating Nodes Programmatically but cannot edit fields using Drupal once created

texts:
I have a collection of nodes that are created programmatically after having created the content type using Drupal. This is the creation code:

    $node = new stdClass();
    $node->title = $vals->title;
    $node->type = "event_type";
    node_object_prepare($node);
    $node->status                       = 1;
    $node->promote                      = 0;
    $node->comment                      = 0;
    // title
    $node->title = $vals->title;
    // body
    $node->body[$node->language][0]['value']   = $vals->body;
    $node->body[$node->language][0]['summary'] = text_summary($vals->body);
    $node->body[$node->language][0]['format']  = 'filtered_html';
    // intro text
    $node->field_event_type_intro = $vals->field_event_type_intro;
    // teaser
    $node->teaser = $vals->teaser;
    // data
    $node->data = $vals->data;
    // nodewords
    $node->nodewords = $vals->nodewords;

    $node = node_submit($node); // Prepare node for saving

    node_save($node);

This seems to be working but when I then click on one of these nodes to edit it it only shows the title in the edit screen. The body and intro are missing.

What am I doing wrong?


texts: What is the nature of list variables provided by "Fetch content flagged by user"?

texts:
On my site (Drupal 7/Flag 2/Rules 2), users can flag taxonomy terms.  I am attempting to write a rule that compares a list of taxonomy terms that I have created with each user's list of flagged terms.

I generated the list of flagged terms by using the Fetch content flagged by user action, which provides a variable of type list of flag items.  However, I cannot directly compare this with my other variable, which has a type of list of taxonomy terms, because when I iterate through the list of flagged terms using a loop in Rules, the current item from the list of flagged terms is not recognized as a taxonomy term.

Is there a way to force Rules to recognize that the flagged item in question is in fact a taxonomy term?  If not, what is the nature of the list of flagged items variable?


texts: How to programmatically print node from a specific author

texts:
I am trying to print all nodes published by a specific author on my page. Anyway knows a way to do so ?

Thanks


texts:
I have the following code:

$a='1';

function check() {
  global $a;

  if ($a == '1') {
    return "1";
  }
  else {
    return "2";
  }

  var_dump(check());
}

When I run this code stand alone, its output is string(1) "1"; when I use the code inside page-front.tpl.php the output is string(1) "2.

Why?


texts: Redirect timer on successful WebForm submition

texts:
I'm asked to introduce auto-redirect (to the home page) on the confirmation page of WebForm (i.e. when user sends data, he gets on the page saying "Thank you! You submition has been received, etc..." ). And I'm asked to make a redirect after some time having past, let,s say, 10 seconds.

Seems that I have to introduce some js altering but I don't know how to do this properly.

Thank you!


texts: How to prepopulate the currency of a commerce_price field

texts:
I want to prepopulate the currency (select list of available currencies) of a commerce_price field.

(edit – specify my question):

I don't want to prepopulate any value (e.g. EUR) for my field as a default value for all new content. I need to have different currency values prepopulated through content-create links out of different views.

Example (I know the syntax doesn't work, that's my problem):

1st Link: http://www.example.com/node/add/contenttype?[curreny-value]=USD

2nd Link: http://www.example.com/node/add/contenttype?edit[title]=EUR

The curreny value should be visible but disabled (not editable) in any prepopulated forms.

Is that possible with the prepopulate module or do I need a hook?


texts: Allow some products to be sold only in bundles (groups) with some other products

texts:
I'm making a commerce site with Drupal 8 and Drupal commerce and I have a not so common request. Some of the products should be available to buy only in groups (bundles) with some other products. E.g. if you want to buy product A in quantity 100 you must also buy product B, product C and/or product D and sum of them (B+C+D) must also be 100. Other way it shouldn't be possible to buy any of them separately.

I saw that there are some Bundle modules (not even sure if they could fulfill this request), but they exist only for Drupal 7.

So is there some module for D8 which will allow grouping products like this. If not what would be the best way to achieve this feature?


texts:
I am new to Drupal, and I am trying to add some behavior to an existing page within Drupal.

Using the admin UI, I created an model with 2 numbers (num1, num2). I then rendered it into a form.

Now I would like to add a third field, and compute using the client the sum of num1 and num2 into this new field. This needs to be done as you type the numbers.

I wanted to use Javascript to do this, but I really don't know where to start. Is there an example on how to simply add some logic into an exiting screen that is generated by the admin tools?

This is more information.

Then, I just add these to fields into a page like so:

Again, at this point I would like to just add the sum of both numbers into a 3ed field that is not there yet (of course my project is much more complex, but this is a simple example). So I was going to add field_number3 into my Content type, and I wanted to do some simple Javascript to calculate the field.

I could really use some step by step examples, to just to know where to place a module, and what code to type in  the module to only add this behavior to my content.

I am very new to Drupal, and I am using Drupal 8.


texts:
I have created some user roles in my drupal 6 website.

Have can set one of them as default role when users register in the site?


texts:
In order to create a search block with autocomplete, I'm trying to use a callback function.
But it doesn't work with my module.
This module is implemented on my homepage which is http://mywebsite.com/lastnews

Could you help me?

Here is my code :

//my module
function search_city_block_info() {
  $blocks['search_city'] = array(
    'info' => t('Search a city'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

//my block
function search_city_block_view($delta = ''){
    switch ($delta) {
        case 'search_city':
            $block['subject'] = t('Search a city');
            $block['content'] = drupal_get_form('search_city_form');
            break;
    }
    return $block;
}

//just for the callback for autocomplete
function search_city_menu() {
  $items['search_city_page_autocomplete'] = array(
    'page callback' => 'search_city_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

//the form with the search field
function search_city_form($form, &$form_state) {
  $form = array();
  $form['City'] = array(
    '#title' => t('City'),
    '#type' => 'textfield',
    '#maxlength' => 60,
    '#autocomplete_path' => 'search_city_page_autocomplete',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

//the values for autcomplete
function search_city_autocomplete($text) {
  $results = array();
  $results['city1'] = 'thefirstcity';
  $results['city2'] = 'thesecondcity';
  drupal_json_output($results);
}


texts: How to log in to site after removing login form

texts:
After I logout. I couldn't login. I didn't assign the block for the user login. I tried out ,

?q=user

$block['content'] = drupal_get_form('user_login_block');

$form = drupal_get_form('user_login');

It displays:

User account Error
The website encountered an unexpected error. Please try again later.

How to get the log in. Please help me


texts: What are the reasons for images going missing without changes made?

texts:
I have a client who is complaining that images which were there are no longer there. I wasn't sure what to think about it, so I asked him to add them again and let me know if it happens again, meanwhile I took note of the file path (/sites/default/files/styles/large/public/map.jpg).

I have now received another email saying they have disappeared, and upon checking the default Drupal broken image can be found within the WYSIWYG, but there is nothing on the actual page display of the node. I checked the file path and the image still exists on the system. There is also no new node revisions, so they have obviously not messed around with it.

Could anyone provide me with a list of explanations on what could possibly have happened here? I'm confused and I have no idea where to start with this problem!

FYI Drupal version is 7.12!


texts: How do I display a search result message that includes filter criteria?

texts:
I have a view to display nodes, with many filters and sorting conditions; that it gets confusing. I want to display the effective filters somewhere, for example refined by X or sorted by Y. is there any way to print the active filters?

for instance consider I have mobile shop, with a view to list phones.there are lots of fields that user can refine using exposed filters. I want at top of page print a message like:

showing phones with X Gb ram and Y screen size and Price Z.


texts: How to view and inspect a Commerce Billy invoice pdf template as HTML, before it's passed to the PDF generator?

texts:
I'm trying to customise a Commerce Billy pdf invoice template. I've seen  Custom PDF template in Commerce Billy which tells me what I need to know about which files to edit to do this.

What I can't see how to do is, see the template as rendered by HTML before it's converted into a PDF. I need to do this to see what CSS classes are being applied where, and because testing changes to the HTML and CSS layout is much easier in HTML and CSS using inspect element tools than constantly re-generating PDFs.

How can I see a Commerce Billy PDF template as it is rendered as HTML before it is passed to the PDF generator? Right now, I'm just guessing about how the rendered PDF will look when I make changes, then repeatedly re-rendering PDFs, which is an inefficient way of working. I'd like to be able to try different CSS changes using developer tools in a browser, then apply those changes to a file and check they apply cleanly, then generate test PDFs.


texts:
I've created a drupal custom form. I've used a select option for bank which get its value from the bank table. I want to store bankID in bankbranch table and which is a foreign key and display bank name in select box but it shows me an error:

  Undefined property: stdClass::$bankID in bankbranch_form() (line 40 of
  C:\wamp\www\emp\sites\all\modules\bankbranch\bankbranch.module).

My code is below:

/**
* Implements hook_permission().
*/
function bankbranch_permission() {
  return array(
    'submit bankbranch' => array(
      'title' => t('submit bank branch'),
      'description' => t('submit bank branch form'),
    ),
  );
}

/**
* Implements hook_menu().
*/
function bankbranch_menu(){
  $items = array();
  $items['bankbranch'] = array(
    'title' => 'Bank Branch Entry Form',
    'type' => MENU_NORMAL_ITEM,
    'access arguments' => array('submit bankbranch'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('bankbranch_form'),
  );
  return $items;
}

/**
* Bank Branch Form
*/
function bankbranch_form($form, &$form_state){
  $query_bank = db_select('bank', $alias = NULL)
    -> fields($alias = NULL, array('bankID', 'bankname'))
    -> execute()
    -> fetchAll();
  $options_bank = array();
  foreach($query_bank as $value) {
    //bankID as key
    *$options_bank[$value->bankID] = t($value->bankname);* /** line for which it shows notice*/
  }
  $form['bankID'] = array(
    '#type' => 'select',
    '#title' => t('Select Bank Name'),
    '#options' => $options_bank,
    '#size' => 1,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchName'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Name'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchaddress'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Address'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['branchcode'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch Code'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );
  $form['ifsccode'] = array(
    '#type' => 'textfield',
    '#title' => t('Branch IFSC code'),
    '#size' => 50,
    '#maxlength' => 128,
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add item'),
  );
  return $form;
}

/**
* Submit handler for the bank_form. Insert entry into the database.
*/
function bankbranch_form_submit($form, &$form_state){
  $branchID = db_insert('bankbranch')
    ->fields(array(
      'bankID' => $form_state['values']['bankID'],
      'brachName' => $form_state['values']['brachName'],
      'branchaddress' => $form_state['values']['branchaddress'],
      'branchcode' => $form_state['values']['branchcode'],
      'ifsccode' => $form_state['values']['ifsccode'],
    ))
    ->execute();
    drupal_set_message(t('Your form entry has been added'));
}

Any suggestions?


texts: Views contextual filters for user term references

texts:
I have two user roles that have term reference fields tied to profiles. One has a single select (user role A) and the other a multi select (user role B), but they reference the same taxonomy.

I have a view that lists all nodes of type C submitted by various users with a single user reference to user role A. My goal is to filter this to those with a user reference who has a term reference in common with a user of role B. The view is accessed by visiting user B's profile page and displayed as a block.

My thinking was to first add a relationship to the single select taxonomy term reference for role A. Then, add a contextual filter that loads the user id from the current URL and puts all the term IDs from the multiselect into the arg, for example 3+5+9. Finally, I would do custom PHP or Taxonomy term validation to see if user role A is in this list.

Setting the argument works fine. I can dsm this and see the correct TID. For validation, custom PHP doesn't seem to work at all. No rows are returned even when I simply do a "return true;" in there. For taxonomy term, I have it set to

Validator: Taxonomy term
My vocab is checked
Filter value type: term id
Action: no results found

Any idea what I'm doing wrong or the correct way to solve this problem?

EDIT: There was a problem with htaccess which explains why return true was failing. However, I still can't quite get the contextual filter and relationship logic down.


texts: Which megamenu supports i18n content translation?

texts: Do you know which megamenu supports i18n content translation?


texts: how to set an absolute position to a view (or div class)?

texts: I have 2 views that displays ads on both sidebars of the page. on top of one of them, is another view that displays articles. the view that displays articles can be a height of anywhere between 20px, and 200px, depending on how many articles there are at the time. I need the ads underneath it to be aligned with the ads on the other sidebar. If I use something like margin-top, it will only work if there are the same amount of articles throughout the life of the site. I was hoping to do something like anchor the view to the bottom, or to set a specific position to put the view.


texts: Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page

texts:
Ryan has some great code that you can programmatically create an order

<?php
global $user;
$product_id = 1;
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid, 'checkout_checkout');

// Save the order to get its ID.
commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);
?>

http://www.drupalcommerce.org/questions/3259/it-possible-drupal-commerce-work-without-cart-module

I have a site where I want to take anonymous donations so I have two problems.

If a user is not logged into the site they get an access denied message
The checkout process asks for name, address etc.

What I want to do is have a page where you confirm the amount then get taken to the payment page. In this case I am using PayPal WPS so redirecting there would be great.

Any advice you could give would be appreciated.


texts: Web forms senders to make their email secure

texts: Make Web forms secure- can we have an option for senders to make their email secure when sending private information back like account numbers, is there an option for this in Drupal or is it possible to create something,


texts: How do I fix File Upload After Upgrading to PHP 7

texts:
I know this question has been asked a thousand times in a thousand different ways, but none of those solutions have worked for me.
Problem: I recently updated from php5 to php7. Whenever I attempt to upload an image (have not tried any other file types) I get the attached
My Setup:

Drupal 8.6.1
PHP 7.2
Windows 2012 Server
IIS 8

Things I've Tried:

I have ensured that IIS users permissions have been set to read/write/modify for the tmp directory.
I have explicitly declared the tmp_upload_directory value in php.ini

upload_tmp_dir = C:\inetpub\wwwroot\tmp

The reason I believe it is PHP (could definitely be very wrong) is because of the first failed item in the error. "The file php3BF5.tmp....."


texts: How to remove height and width attributes from CCK ImageField tags?

texts:
I am using Drupal 6 with the CCK ImageField module.  By default, it outputs the height and width of the image as attributes of the tag. For my current project, I'd like to be able to override those with CSS. I have not been able to determine which theme function adds those attributes.

Which functions/templates do I need to override to remove those tags?


texts: Why does Drupal not register Menus Nor Links?

texts:
One of the website that I manage the menu system is not working. I have installed many modules (including the commerce modules) and are not being displayed on the menu. However, all modules links (and commerce) works, if I type it on the URL.

After troubleshooting a little bit more I figure out that this is not only for commerce. I created a new content type and is not been display on the node/add page  or in the admin_menu. And once again I'm able to go to the page if I type the URL.

I click on rebuild menu, I flush all caches and still not been register. I do not see any Drupal logs errors.

How can I address this problem ? I cannot expect the sysadmin to know all the URL.

Update 3/27/2015

I'm now using the latest Drupal (v7.35) and I noticed this at first on 7.34.

Like I mentioned before it is not only on the menu. So I do not think the admin_menu is the problem. I remove the module admin_menu and use the toolbar module. But there are missing links on the pages that are been created for the latest module that I have installed. So any module that I enable from now on it would not register the pages.

Update 4/3/2015

I'm now using the latest Drupal (v7.36) and I noticed this at first on 7.34.

I disable/uninstall and enable drupal core menu module and still not fix this issue. Someone from the Google + community suggested that this issue may be cause by the jquery updated I try to used different jQuery version and still have issues. In addition, I try to follow this How to completely wipe and rebuild drupal menus? and to rebuild all my menu and did not work.

I strongly believe is need to be something with the hook_menu not working on my Drupal website.

Update 4/4/2015

I notice that if I add a new content type it would not appear the links on the node/add nor under the content menu. However, it appear in the page admin/structure/types and in the menu under structure -- > Content Type.

Some more updates to address one of the suggested answers to try to get my issue reolved:

This is single site installation.
I do not think is because of the memory_limit. Because I have managed bigger sites that does not have this issue. I did try it out and it did not help. I.e in my setting.php I set it up to 300M and on my php.ini as well. After that I cleared caches, run cron, restart the webserver. And still nothing.


texts: Loading more content in mobile (Slider) - Views core module

texts:
I am using the view core module to view the featured articles, latest articles and more stuff in my project, it is rendering 3 articles and the load more button to load more content using ajax, This is working great in Desktop, However in Mobile, the load more button doesn't exist (As per website design) and the articles are displayed in a slider. I am hiding load more button using CSS, the user has no way of loading more content!!

1st Approach: Load more content using ajax.

How can I automatically load more content after the user slides 2 or more slides ? I can easily detect when the user slides to the 2nd slide using jquery but how can I load more slides dynamically using ajax? Do I have to load more content by myself or does Drupal 8 have a way of doing this?

2nd Approach: Make 2 blocks, one for desktop, one for mobile.

I thought of doing 2 separate views blocks:

Desktop view block: 3 items and load more button

Mobile view block: all items

But this doesn't feel right, and I will have to toggle between them using CSS which means the content will be fetched by network anyway, So this approach is not correct.

I could not find how to hide or show a block depending on view width without CSS.

If there is another approach please tell me.


texts:
This looks appropriate for D7, but add_where doesn't exist in D8. What should I use?
/**
 * Filter out the current node from the view query
 */
if ($view->id() == 'videos') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node) {
        $query->add_where(0, $node->ID(), 'nid', 'NOT IN');
    }
}


texts:
I think I am missing something really silly here. I am trying to learn theming in drupal. So I downloaded a "starter" theme called Genesis and installed it. This theme has a barebones header and footer. And in the middle the content area is split into left sidebar, main content and right sidebar.

I created a panel page with 'flexible' layout. It has only one region defined and inside it I placed a custom view I had created earlier. Now when I hit this panel page url, it shows up correctly, but inside the main content area of theme. I mean the header, footer, left and right sidebars are still visible.

My question is: By default do panel pages render inside main content area? How can I customize a panel page such that I can do away with the header, footer or sidebars if I want to?

Appreciate any help!!


texts:
I'm using Drupal CKEditor module 7.x-1.13 and CKEditor 4.3.2.
Everything is installed and appears to work fine... except that there are some buttons that don't appear despite being configured to do so, notably "Select All" and the justify left/right/centre/justified buttons.
Here are the buttons as configured:

And here are the buttons as they appear:


texts: How to integrate messaging into a custom module?

texts:
I'm working on a custom module to handle time off requests for an intranet site and I'd like to be able to have the module fire off email notifications to a configurable list of users -- specifically, the requesting user's supervisor and also CC: an HR representative.

I've looked at Notify and Notifications and I assume that one or both of those expose an API but I can't find any documentation about how to integrate that into a custom module. I also looked at Rules, though I'm not sure that's the best solution.

I could always do a completely custom job but I'd hate to reinvent the wheel if there's a better Drupal-style solution like hooking into one of these existing notification modules.


texts: How do I remove the default node path when using a path alias?

texts: When I add path aliases, how do I remove the system path (/node/[nid]) in Drupal 8, to avoid Google to index the page twice?


texts:
I was curious after stumbling upon this particular construction of a responsive menu.

How was this responsive menu toggle menu created? is it via a module or just pure css / javascript?

http://picturefill7weblinc.h011.attiks.com/node/1


texts: How to switch language on pages containing charts created using Forena?

texts:
I have created a chart using Forena Reports. I have created a menu with this chart as one of the links.

I have also installed the Language Switcher Dropdown module for choosing between 3 languages. When I choose between any of the languages, the page will get refreshed and I will be able to see the transalated version.

But this is not happening when I am in the chart page. When I choose other language page is not even getting refreshed also language is not getting changed. When I go to other pages and try the same, everything is working as expected.

Note: When I go to the chart page I can see this error in console:

  Uncaught TypeError: $(...).dataTable is not a function

which is coming from the datatables.js file inside the forena report.


texts: How to access a parent paragraph twig file from a child node twig file?

texts: In my bootstrap theme, I am trying to make the id of the paragraph the same as an attribute for each of the child nodes, so an accordion will work properly. I have tried looking at doing it through hooks, but I can't seem to access the paragraph data from my node hook.


texts: Display solr result by specific field order

texts:
I am implemented the Apache Solr with Search API module.
Everything working fine but now requirement is to show solr result by specific field order.

I have total 4 fields in content type

Field 1
Field 2
Field 3
Field 4

Now solr show result random order from this field i.e any field coming on top.

I need to show result by field order. i.e display all result on top by matching "field 1" then "field 2" and so on.. Anyone can help me to achieve this result...


texts: Overriding the Blog username breadcrumb in the native Blog module

texts:
I want to disable the blog username in the breadcrumb which reads:
Home > Blogs > John's blog > Blog post

I have found the function in the core Blog module:

/**
 * Implements hook_view().
 */
function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => format_username($node))), 'blog/' . $node->uid)));

  }
  return $node;
}

How should I best override this function in my theme?


texts:
Following instructions here, I used the command drush dl drush to install the newer version of Drush. Then, when I attempted drush omega-export (the reason I was upgrading was to have access to these newer omega commands) I received a message indicating that drush was still pointing to the older version of drush.

If the server was based in my home computer environment (win7) I would change the PATH variable to point to the newer version. However, since the server I am working on is remote (onyxServers, typical LAMP stack) I am unsure how to make the drush CLI point to the new version.

Can anyone point me to  a resource? If it was my own linux machine I would be able to figure it out but being hosted confuses things a bit.

UPDATE: I have examined the output of the 'env' command, and noticed that the location of drush, new or old version, is not listed in the PATH variable:

  PATH=/usr/local/jdk/bin:/home/dukkha/perl5/bin:/usr/kerberos/bin:/usr/lib/courier-imap/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/home/dukkha/bin

Is it possible that the path to drush is stored within the drush shell or something?


texts:
I need to "migrate" all quiz results from one website to a new one. The quiz ID is different between sites, and therefore, copying over the table from mysql won't work. However, I've made sure that user IDs are the same.

The new website isn't launched yet and there is a lot of flexibility for how I need to set things up in order to migrate in the most ideal way.

Edit: Alternatively, is there any reason I shouldn't just migrate the quizzes with the same node ID?

Edit2: I am using quiz version 7.x-5.1 on the new site but if they have to be the same, I'll have to rebuild the training feature with the version on the old site, which is 7.x-5.0-alpha4+77-dev. We have about 25 quizzes with 10-30 questions each.


texts:
Long ago I got a message about updates to my modules. I've updated the modules.
But I received a message to update the database.

I want to run the update.php script but I encounter the following error message:

  Server error.

  The website encountered an error while retrieving http://MYSITE.COM/update.php. It may be down for maintenance or configured incorrectly.
  Here are some suggestions:
  Reload this webpage later.

  HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

I do not remember which modules got updated.
Please help me.


texts: Add option values to field that already has data

texts:
I created a content type with a field "Category".

In that field I added two values:
- Books
- Movies

I inserted data in this content type and I have a view showing the content per category.
Now i need to add a new value "Series" but it shows this message:

There is data for this field in the database. The field settings can no longer be changed.

What can I do?

Thank you in advance!


texts: Create a Form in a Block using API that sends captured data to email

texts:
Possible Duplicate:
  Send email of form data?

So I have a simple three field form which I've created in HTML/CSS, see here:

Now I want to put this into a block module, generate the form fields using Drupal Form API (is this appropriate or should I just stick with my existing HTML markup?). And on submission of the form I want it to email the details to a designated email. Is Drupal Triggers appropriate for this, if not, what is?

Any guidance on where to go with this would be amazing. Thanks so much for your time :)


texts: How to create something like a textual "add other term" for taxonomy terms?

texts:
How can I setup taxonomy terms so that you can have an extra field called "others", where you can add your own terms if the term you want to use is not defined yet as a term of that taxonomy?

I have researched and came across a module called Select(or other). It does what I want, but it is in text.

My problem now is that I've added so much taxonomies for my student record content type (like countries, or faculties). So I've gone too far and cannot cancel (undo) the taxonomies and replace them with the module I found.

Any suggestion of how to add something like such extra field to the existing taxonomy module?

I imagine that when users insert data, they might not find appropriate terms to choose from. So I want to give them an option that "if current term don't apply to you, then please insert your term manually".

I'm still newbie in Drupal7 and PHP programming.


texts: How can I get a list of the roles in a system, via the REST API?

texts:
Similar to How to Retrieve all Forums, how can I retrieve the list of roles in a system via the Services REST API?

This is Drupal 7, Services 3.x.

Are roles terms in a taxonomy vocabulary ?


texts: changing a MySQL query to a drupal query any ideas

texts:
I'm trying to change the following query to a drupal db_query:

SELECT first_name, SUBSTR(first_name,1,3) AS firstname_substr FROM civicrm_contact WHERE id != 'NULL' ;

I have tried this, but its not working:

$firstname_substr = $query->addExpression('SUBSTRING(cc.first_name,1,3)','cc.firstname_substr');

Below is the function I am trying to add it to:

function search_pcp($name, $from = 0, $count = 5){

  $query = db_select('civicrm_pcp', 'pcp');
  $query -> join('civicrm_contribution_page','cp', 'pcp.page_id = cp.id');
  $query -> join('civicrm_contact','cc','pcp.contact_id = cc.id');
  $query -> addJoin('LEFT OUTER','civicrm_entity_file','cef', 'cef.entity_id = pcp.id');
  $query -> addJoin('LEFT OUTER','civicrm_file','cf', 'cef.file_id = cf.id');
  $query -> condition('pcp.is_active','1','=');
  $query -> condition('cp.is_active','1','=');

  $db_or = db_or();
  $db_or->condition('cc.first_name',  $name, 'like');
  $db_or->condition('cc.last_name',  $name, 'like');

  **//$db_or->condition($firstname_substr, $name);**

  $query -> condition($db_or);

  return $query->execute();

}


texts: getting 404 error while developing an example module

texts:
I have created custom module named hello
my files are

hello.info.yml  is

name: Hello
type: module
description: 'My first Drupal 8 module.'
package: Awesome modules
version: 1.0
core: '8.x'

hello.module file is

<?php

use Drupal\Core\Routing\RouteMatchInterface;
function hello_hello_world() {

    return t('Hello Drupal 8 World!');

}

** hello.routing.yml** file is

hello.content:
  path: '/hello'
    defaults:
       _controller: '\Drupal\hello\Controller\HelloController::sayhello'
  requirements:
    _permission: 'access content'

and last one is HelloController.php is under hello/src/Controller folder

<?php

namespace Drupal\hello\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 *
 */
class HelloController extends ControllerBase {
    /**
     * [sayhello description]
     * @return [type] [description]
     */
    public function sayhello() {
        return array('#markup' => hello_hello_world());
    }
}

when we browse this page mywebsite.com/hello it gives a 404 error page.

Note: module is successfully enabled from admin


texts: How can I add a taxonomy terms as a CSS class to my views?

texts: I would like to add a taxonomy term as a CSS class to each view result. How can I do that?


texts: Contact form block with data from the page the blocks featured on

texts:
So I have a content type "Real Estate." On the view for a "Real Estate" node, I want to have a contact block in the right side bar that has a feild for the node id of this specific "Real Estate" node.

An example of the feature I'm trying to make can be seen here

This problem has two parts which I'm not sure how to do. The first is that I don't know how to make a block for a contact form. I know drupal has a default Contact module but I'm not sure how to turn this into a block or even if that is the best way to go (maybe WebForms module can help?) Second is that I'm not sure how to pre-load the node id into the form. I'm sure that this would require a hook of some kind but seeing as I don't know how to make the contact form block, I don't know what hook to use.

Any help would be much appreciated. Thanks!


texts: How to run PHP code only once on node creation?

texts:
I'm using Drupal 7, and the Computed Field module.
I want to run code just once, when the node is created.

Is there any specific function?


texts: How can I add an unescaped script tag and contents to a page?

texts:
I would like to add to my pages the structured data in JSON-LD (https://developers.google.com/search/docs/guides/intro-structured-data)

Basically, what I need to do is to add somewhere in the HTML for, let's say a basic page, a snippet like the following:

<script type="application/ld+json">
{  "@context":"http://schema.org",
   "@type":"WebSite",
   "name":"Site name",
   "alternateName":"Site alternatime name",
   "description":"Site description",
   "keywords":"list of keyword",
   "inLanguage":"en",
   "url":"http://www.example.eu/en",
   "potentialAction":{
   "@type":"SearchAction",
   "target":"http://www.example.com/en/find/{search_term_string}",
   "query-input":"required name=search_term_string"
   }
}
</script>

I've tried to use the full HTML input but the snippet gets (kind of) escaped with the CDATA and google cannot parse it.

So, how can I provide that snippet without any escaping?


texts:
I have a custom search form which appears in the modal and is accessible only to logged in users.
The ajax url of the form is /my/custom/search/modal/{nojs}.
The router definition is the following one.
mymodule.my_custom_search_form:
  path: '/my/custom/search/modal/{nojs}'
  defaults:
    _form:  '\Drupal\mymodule\Form\MyCustomSearchForm'
    _title: 'My Custom search'
    nojs: ajax
  requirements:
    _user_is_logged_in: 'TRUE'

How do I redirect users to the login page when the anonymous user tries to access /my/custom/search/modal/{nojs} via an AJAX call?


texts: Displaying a standard picture when user has not uploaded a picture

texts:
I am using the following code.

if ($logged_in) {
  $user = user_load($user->uid);
  print theme('image_style', array('style_name' => 'thumbnail_scale_n_crop_120_x_120', 'path' => $user->picture->uri));
}

It displays the user's picture.

How should I modify it so that so that when the user has NOT uploaded or has deleted his picture a standard "no photo" picture is displayed instead as in:

$no_avi = "http://example.com/sites/default/files/nophoto.jpg";
echo("<img src=\"$no_avi\" />");

The User Picture Field module does not provide this capability.


texts: Integrating Video.js with Google Analytics

texts:
I'm wondering if anybody has gotten the Video.js module/library to play nicely with Google Analytics? I'm trying to do some integration via this plugin (https://github.com/mickey/videojs-ga), but am hitting a roadblock. I've added the script into my theme as second-to-last in the execution order, followed by another script consisting of the inline code noted in the example (as the final script on my page):

<script>
videojs('video', {}, function() {
  this.ga(); // "load the plugin, by defaults tracks everything!!"
});
</script>

At this point I think it's almost working, but chrome is throwing "Uncaught TypeError: The element or ID supplied is not valid." I've also tried replacing "video" on the above code with the ID of the video on the page that I am testing, and I'm getting the same error. I feel like I'm close, but I'm not sure what needs to be tweaked to get it working. Any ideas?

Right now I'm testing on http://mattweinercreates.com/video-js-testing, i you want to check out my environment.


texts: Alter the exposed filters of a view, based on the view result

texts:
I have a view that displays matching nodes, based on contextual arguments.

I'd like to create an exposed filter that filters by node title, displaying a drop down (select) menu with options for every node in the result set.

I can modify / set the contents of the exposed filter using hook_form_alter, but the views query hasn't executed when this hook is called, so I don't have access to the result set.  If I use hook_views_post_execute then I have access to the result set, but the exposed filters form has already been rendered.

I know that I could write an EntityFieldQuery to select the nodes and set them within hook_form_alter, but that isn't very DRY as I would effectively be re-writing (and executing) the same query that Views will be executing anyway.

What's the best practice way to achieve what I'm looking for?


texts: How do I add custom tab in the user profile page?

texts:
I need to add a custom tab in user profile page. I defined my route like below:

mymodule.routing.yml

mymodule.account:
path: '/user/{user}/custom'
defaults:
  _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
  _title: 'Custom Settings'
  user: \d+
requirements:
  _permission: 'access content'

mymodule.links.task.yml

mymodule.account:
  title: Mymodule Settings
  route_name: mymodule.account
  base_route: entity.user.canonical

mymodule.links.menu.yml

mymodule.account:
  title: My module Settings
  parent: entity.user.canonical
  route_name: mymodule.account

Then after clear cache tab is appearing in the profile page. But when I open the url /user/1/custom I see the page not found message.


texts: Why is there a convention to use test-specific namespaces for unit tests?

texts:
My team and I have noticed that the Drupal convention is to create a separate namespace for unit tests (as opposed to the namespace define by, lets say, the custom module we are testing).

If they shared a namespace then we could, for example, easily override a function like t() for our tests. I know there are lots of ways to handle things like the t() function, but this convention of creating a new name space eliminates this particular option. Can anyone speak to why? What is the benefit?


texts: How to fix incorrect average ratings for Fivestar?

texts:
I am using Voting API with Fivestar.  On my site users can comment on a node and leave a rating with the comment.  These are aggregated and an average vote is displayed at the top of the node.  The average rating for some of my nodes does not match what the average would be if you summed up the comment ratings and divided by the number of comments.  Also the count is wrong.

I believe this happened because I manually converted an old Drupal 6 site to Drupal 7 so I manually entered some old reviews.  Because I entered them from the same IP and within the threshold of time I believe the module does not count them.

I'm comfortable running SQL queries to fix this.  I was able to enter the correct average and count records in the votingapi_cache table.  This temporarily fixed the problem, but later I deleted some spam comments, and then the rating was messed up again (I guess maybe deleting causes the votingapi_cache table to be rebuilt?)

What is the correct way to fix this?

UPDATE

So there is more to the story.  I just spent some time manually adding the records into the votingapi_vote table.  Then I added a new comment with a vote through my drupal site.  This caused the votingapi_cache to be rebuilt and I saw the the average vote and vote count were correct.  I thought great problem solved.

Then I deleted my test comment and immediately the average and vote counts went to zero.  Examining the votingapi_vote table which I had just manually added records to, I saw that all records for that node id were gone.  So deleting a comment deletes all records in votingapi_vote table.  Seemed fishy so I searched and found it's a bug in the fivestar module: Deletion of Anonymous Comments with Fivestar rating results in deletion of all votes for entity.

Pretty horrendous bug if you ask me.  Don't think it's fixed in the module but that bug link has a patch for it which I will try out.


texts:
Background + question

I want to port entdispfieldui to Drupal 8. (issue)

The module allows a site builder to add new entries into an entity view mode, configure and position them among the regular fields. These entries exist per view mode / bundle / entity type.

I am wondering what would be the best way to achieve this in Drupal 8. Is one of the ideas below suitable? Why would I use one over the other?

Ideas so far

Idea 1: Extra fields + config entities

hook_entity_extra_field_info() allows to insert "pseudo" fields per entity bundle, but across view modes. The idea would be to use hook_form_alter() to remove the items from those view modes where they don't belong.

I found some documentation on extra fields here: https://www.webomelette.com/creating-pseudo-fields-drupal-8

Entries would be stored as config entities, with keys to determine to which view mode they belong.

For this, I started looking at https://www.drupal.org/docs/8/api/configuration-api/creating-a-configuration-entity-type-in-drupal-8

Idea 2: Learn from field_group and Display suite

field_group does something similar to what I am trying to do. Except that the entries are not pseudo fields, but groups. But still, these are entries or "things" that exist per view mode, and can be created and deleted.

But I found that field_group does not use a config entity type for this. Instead, in field_group.entity_display.schema.yml, I find this:

core.entity_view_display.*.*.*.third_party.field_group:
  type: sequence
  label: 'Field group settings on entity view'

Similar lines can be found in ds.entity_display.schema.yml or field_layout.schema.yml. Although these do not use type: sequence. I think this is because they store settings for the view mode itself, not for entries within the view mode.

So I wonder, what does the core.entity_view_display.*.*.*.third_party... mean, and why would I use this + type: sequence, instead of a config entity type?

And if I use this method, would it still make sense to work with hook_entity_extra_field_info() ?


texts: How to create dynamic contents with view

texts:
I have to create some different pages in Drupal 7.
I need a different header and a custom text for the pages appearing in the same block, so I thought that it would be useful to create a view.
I did not develop that website, is it  the right way to do that?

I will explain it better.
I have to do 4 landing pages with the same structure.
I created a webform block for the right block. It will be the same on the four pages. Now I want to create two more blocks, one for the header and the other one for the text. I'd like to change the block content in the different pages.
How can I do it?