texts: Roles and Permission creation programatically inside module

texts:
I am trying to create drupal 8 roles and permissions programatically. My current approach is to have a module that when install it will generate those set of roles and permissions defined by the  module. It would be more like a background Module, where no form is needed or anything. My problem lies that I really don't know where to start the the roles creations since no form is needed, I mean should I create them inside a hook?, if so which hook?, any other place?

I really don't know if this is the best approach, still a newby on drupal 8. Any suggestions will be greatly appreciate it.

Thanks in advance


texts: How to set value of file field with entity_metadata_wrapper

texts:
How do you set the value of a file field when using the entity_metadata_wrapper?

I've tried doing this in code:

$file = new stdClass();
$file->uid = 1;
$file->uri = $file_path;
$file->filename = basename($file_path);
$file->filemime = file_get_mimetype($file_path);
$file->filesize = filesize($file_path);
$file->status = FILE_STATUS_PERMANENT;
$file->display = '1';
file_save($file); // I also tried: $file = file_save($file);

$node = array(
  'type' => 'news_item',
  'uid' => 1,
  'status' => 1,
  'comment' => 0,
  'promote' => 0,
  'language' => 'en',
);

$entity = entity_create('node', $node);

$ewrapper = entity_metadata_wrapper('node', $entity);

$ewrapper->field_document->set((array) $file); // I also tried: $ewrapper->field_document->set($file);

$ewrapper->save(true);
entity_save('node', $entity);

But I get this exception:

EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of C:\wamp\www\drupal\sites\all\modules\entity\includes\entity.wrapper.inc).

Any help is very mych appreciated.


texts: Why doesn't my code for passing a PHP variable to JavaScript work?

texts:
I am using the following code, but the JavaScript console prints undefined instead of the value of settings.api_key. What is wrong in the code I am using?

libraries.yml file

stripe_files:
  version: 1.x
  js:
    https://js.stripe.com/v2/: { type: external, minified: false }
    js/custom_stripe.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
  css:
    theme:
      css/custom_stripe_integration.module.css: {}

JavaScript file

(function ($) {
    Drupal.behaviors.stripe = {
      attach: function (context, settings) {
        alert('hello4');
         console.log(settings.api_key);
      }
    };
})(jQuery);

Form class

/**
 * @file
 * Contains \Drupal\amazing_forms\Form\ContributeForm.
 */

namespace Drupal\custom_stripe_integration\Form;
use Drupal\Core;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\SharedTempStore;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Locale;

require_once 'modules/custom/donate_gateway/vendor/autoload.php';

/**
 * Contribute form.
 */
class StripeSponsorForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'stripe_sponsor_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state,$nid = 0) {
    $config = $this->config('custom_stripe_integration.settings');
    $api_key = $config->get('stripe_api_key');

    $form['#attached']['library'][] = 'custom_stripe_integration/stripe_files';
    $form['#attached']['drupalSettings']['api_key'] = $api_key;

    return $form;
  }
}


texts:
how the title says I would like to trigger javascript (jQuery) event from generated Drupal form button. I already add an id to the button and added the javascript in theme file like so:

$form['dialogCreateButton'] = array(
    '#type' => 'button',
    '#value' => t('Create'),
    '#ajax' => array(
        'callback' => 'form_kalendar_dialog_validate',
        'progress' => array(
            'type' => 'throbber', // needs to be defined
            'message' => t("Please wait..."), // instead of a message insert a javascript
        ),
    ),
);

and the javascript:

jQuery("#edit-dialogsavebutton").bind('click',function(event) {
    if(jQuery("#dialog-event-title").val().length == 0){
        focusElement.children("#eventTitle").text('(No title)');
    }else{
        focusElement.children("#eventTitle").text( jQuery("#dialog-event-title").val() );
    }
    jQuery('#dialog').dialog('close');
});

also with Drupal js:

Drupal.behaviors.rr = {

    attach: function(context, settings) {
        jQuery('#form-kalendar-dialog').once().ajaxComplete(function(event, xhr, settings) {
            console.log( event );
        });
    }
}

Only after several clicks the event is triggered, it acts very strange...


texts: How to obtain a list of JS files from enabled modules, or expose such list from a theme as library?

texts:
I'm in the process of extending jQuery Multi module. Libraries API libraries was built in, I have already added support for JavaScript libraries provided by modules, so with minimal cooperation on the side of modules' authors I have that part covered. Now time to add themes to the list - and I'm stuck.

I found no way to make a theme use hook_library() and by the API docs it's a module hook, so I can't use method I used for modules.

I can use list_themes() to list themes, but how to see a JS files?


texts:
I have created two logo block in left and right in my page.tpl.php page.
I am not able to see admin login.

Please guide me.


texts: Change Views Display Title Programatically

texts:
I had a similar question recently, related to changing the path on a Views Display. Following this reasoning (as well as other examples I've seen), I assumed I could follow a similar approach. Unfortunately, that doesn't seem to be the case.

Related question for reference: Change Views Path Programatically

What I currently have:

$view = \Drupal\views\Entity\View::load('custom_view');
$display =& $view->getDisplay('page_1');
$display['display_options']['title'] = 'My Custom Title';
$view->save();

However, this does not seem to alter the title of the Display. I've attempted a method of changing the Display title in a Views hook, at that works correctly, but I'd like to be able to change the title without relying on actually viewing the View to utilize its hooks. In addition, I believe this would set the title for all Displays, which I don't want. Working example:

function my_moudule_views_post_render(ViewExecutable $view) {
    $view->setTitle('My Custom Title');
}

Following this approach, I attempted to utilize the \Drupal\views\Views::getView() method, but was unsuccessful.


texts:
In this article the first instruction is

  On every site, run drush vd to turn the Views settings to the advanced mode.

What does this mean? A Google search for "Views advanced mode" yields mostly just links back to this article. What is "advanced mode"?


texts: How to implement stateless authentication

texts:
I'm having a big problem with Drupal 8, I want Drupal to trust a downstream reverse proxy that performs authentication against a third party provider, then passes a JWT in a X_ID_TOKEN header.
As I didn't find any module that behaves as an authentication provider that trusts HTTP headers to authenticate the user, I developed a provider myself which is implemented as follows:
public function applies(Request $request) {
  // If you return TRUE and the method Authentication logic fails,
  // you will get out from Drupal navigation if you are logged in.
  $trusted_host = "127.0.0.1";
  $headers = $request->server->getHeaders();
  $server_addr = $request->server->get('SERVER_ADDR');
  return ($server_addr == $trusted_host) && $headers && $headers['X_ID_TOKEN'];
}

public function authenticate(Request $request) {
  $headers = $request->server->getHeaders();
  $jwt_token = explode('.', $headers['X_ID_TOKEN']);
  $user_data = json_decode(base64_decode($jwt_token[1]), true);
  if(!$user_data && !$user_data['email']){
    return NULL;
  }
  $users = \Drupal::entityTypeManager()->getStorage('user')
    ->loadByProperties(['mail' => $user_data['email']]);
  $user = reset($users);
  if ($user) {
    $uid = $user->id();
    $rids = $user->getRoles();
    $account = User::load($uid);
    return $account;
  }else{
    /** @var \Drupal\user\Entity\User $account */
    $account = User::create([
      'name' => $this->generate_username($user_data),
      'pass' => user_password(),
      'mail' => $user_data['email'],
      'init' => $user_data['email'],
      'status' => 1,
    ]);
    $account->save();
    // Store the newly created account.
    $this->save_user_info($account, $user_data);
    return $account;
  }
  return NULL;
}

Then the service is registered like this:
services:
  authentication.trust_openid_auth:
    class: Drupal\trust_openid_auth\Authentication\Provider\OpenIDAuth
    tags:
      - { name: authentication_provider, provider_id: open_idauth, priority: 0, global: TRUE }

This sort of works, but the pages we are rendering contain user personal data, and they are being cached by some Drupal internal cache. This cache is "per user" thanks to the native Drupal session cookie.
Problem: this cookie seems to be randomly set (when it's not there it randomly appears when navigating). When the session cookie is not set, the cache is global and results in rendering a page that contains the personal information of the last user that successfully rendered the page (not necessarily the current user!)
I have read that the session cookie starts existing when data is attached to the PHP session, which I'm not in control of.
I'm pretty lost at this point, the two solution I thought of are:

Tell Drupal to trust a remote Cookie (set by the downstream reverse proxy) as the session Cookie, this cookie would contain the user's JWT
Force the Drupal session Cookie even if there is no data attached to the session, just to contextualize the cache

The first solution would be ideal but I'm not sure how to achieve it. Any help on this would be welcome!


texts: Pre-populate Commerce Shipping Cart using a link

texts:
I need capability to pre-populate commerce cart using a link (preferably add to the cart if one already exists).

For example a link like http://aziteez.com/cart?add_product=prod1+prod2 should add prod1 and prod2 to the existing cart of the user on my website.

Thanks in advance.


texts: Getting 401 / 406 error from node creation with authentication

texts:
I am trying to create nodes with authentication with the services module enabled. So far I have done following things:

Get services token from http://localhost/drupal/services/session/token.
User authentication: I did trigger login web service and in return I got session name, id and complete user information. I called this web service by passing X-CSRF-Token which I got from previous web service. (http://localhost/drupal/myendpoint/user/login.json`)
Node creation: I want to create article content type node. I am passing fields values in JSON and CSRF token and session information as following. (http://localhost/drupal/myrest/node.create)

Body (application/x-www-form-urlencoded)

{
   "title":"Created through service",
   "type":"article",
   "body": {
      "value": "
test
\n",
      "format": "filtered_html"
   }
}

Headers

X-CSRF-Token: bla bla bla
`SESSion name: bla bla bla

The response I received from node create web service is the following:

  Status Code: 406
     Date: Fri, 04 Dec 2015 23:43:31 GMT
     X-Content-Type-Options: nosniff
     Server: Apache/2.4.9 (Win32) OpenSSL/1.0.1g PHP/5.5.12
     X-Powered-By: PHP/5.5.12
     Content-Type: text/html
     Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
     Connection: Keep-Alive
     Keep-Alive: timeout=5, max=100
     Content-Length: 0
     Expires: Sun, 19 Nov 1978 05:00:00 GMT

Could you please let me know what I am doing incorrect while triggering node create web service?


texts: Node is not created, but nid is returned

texts:
I have this code in my module.

  $node = new stdClass();
  $node->title = "YOUR TITLE";
  $node->type = "page";
  node_object_prepare($node);

  $node->language = 'it';
  $node->uid = 1;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;

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

  return "Nodo 222: " . $node->nid;

When I execute this code, it returns "Nodo 222: XXX," where XXX is an integer. If I execute it another time, I get XXX+1. When I try to load node/XXX or node/XXX+1, Drupal give me a Page not found error.

I have seen the "node" table in MySQL (via PHPMyAdmin), and nids XXX and XXX+1 are not present. When I create a page via node/add/page, the new nid is XXX+2 and it is saved in the "node" table too.

I have some modules installed (commerce, rules, logintoboggan and others), but this is the first time that I see this strange behavior.

So, where is my error?


texts: Ajax submission leads to => An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports

texts:
So i'm trying to submit a form using ajax, in my form i have the following:

        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('OK'),
        '#button_type' => 'primary',
        '#prefix' => '
',
        '#suffix' => '

',
        '#attributes' => array(
            'class' => array('proximabold', 'tc', 'transition', 'no-underline', 'ph3', 'pv2', 'mb2', 'dib', 'white'),
        ),
        '#ajax' => [
            'event' => 'click',
            'callback' => '::updateTable',
            'wrapper' => 'table-wrapper',
            'progress' => [
                'type' => 'throbber',
                'message' => t('Verifying entry...'),
            ],
        ],
    );

and a simple updateTable function:

public function updateTable(array $form, FormStateInterface $form_state) {
    return "Hello World";
}

But when i click on submit i get the error:
An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports.

I knew that the error is server side (Maybe i'm wrong), so i went to php.ini (i use PHP7) and update the following lines:

post_max_size = 6144M
memory_limit = 6144M
upload_max_filesize = 6144M
max_file_uploads = 1000

but without luck, this configuration shouldn't be necessary as the request size is only 1.5KB


texts:
I have an angular front end with D8 backend. I am populating a content type that has a Date field. I am successfully creating the content-type with the all its fields including the Date field. The format I am sending via POST looks like 2017-07-07. It gets saved and I can even retrieve the data.

The problem is when I edit or view the node via drupal admin, the date field is empty. If I devel the node, the value I sent is set on the field. It just will not display via in drupal. What format should I be sending the date field so it will save and populate the form.

In JS, I am sending the date like so:

var start = new Date();
var params = {
  start: {value: start.getFullYear() + '-' + (start.getMonth() + 1) + '-' + start.getDate()}
};
$http.post(API + 'entity/node', params); //etc


texts: What will be the post parameter when specifying vocabulary term?

texts:
I am trying to create a drupal node with a iphone app via rest server. I want to send the request to drupal as json.

I have added a taxonomy vocabulary for categorizing the nodes. Specifying a category is mandatory when creating node.

  My request url is
  drupal site/ep/node.json

  Post parameters
  node[title]=mysample&node[type]=story&node[body]=sample body&node[???]=myCategory1

I specified title, body, and type....but what will be the parameter name to specify the term of my vocabulary (i.e. category name)?

I tried node[taxonomy], node[term], node[vocabulary], but no success. Please help!

  Config:
  Drupal 6.26
  REST Server 3.0


texts: How to translate a menu item in Main Menu with a path to a page View

texts:
I'm sure I've done before, but I'm working in a fresh drupal installation and I guess I missed some configuration related to translation.

1) I created a new View which generate a Page.
2) I set No menu for Menu  (see image 1)
3) I set /inmuebles for Path  (see image 1)
4) In the Main Menu I added 2 links one for each language (english and spanish)  (see image 2)
5) Each link are set to the correct language (see image 3)
6)The problem: both link are shown in both languages. (see image 4)

Of course I need the links to be shown ONLY in their respective languages.

Image 1

Image 2

Image 3

Image 4


texts: entity_load not fetching the updated column

texts:
I've a custom entity {my_table} and added a new field in schema file as follows

/**
 * Add {new_column} field to {my_table} table.
 */
function MY_MODULE_update_7100() {
    $table = 'my_table';
  $spec = array(
    'type' => 'int',
    'description' => "blah blah",
    'size'=> 'tiny',
    'default' => NULL,
  );
  db_add_field($table, 'new_column', $spec);
}

When I ran update.php the database table column got updated.

But the problem is when I run 'entity_load' it's not fetching the added column to the object.

$get_entity = entity_load('{my_table}', array(184));
dpm($get_entity) // showing all columns, except the new_column

I've cleared the cache but no luck.
Any suggestions would be much appreciated.


texts: "Send email" action not working to send email to poster of comment

texts:
I have successfully set up email notifications on my client's blog for administrators when new comments are posted and am now trying to set it up to send a thank-you email to the poster of the comment as well. I set it up using triggers and actions as described here.

I put in [comment:author:mail] in the "Recipient" field on the action configuration form as suggested in the note right below that field, but it seems that it never sends the email. I initially tested it using my own email address and it worked fine, then I posted a comment as an anonymous user using two different email addresses of mine but never received an email. Why is [comment:author:mail] not working? I'm using other variables in the body of the email (e.g. [comment:node:title]) and they're working fine.

I tried using Maillog as @tenken suggested below, which verified that the problem isn't with mail delivery but rather with the email not being populated correctly:

Here's a screenshot that shows the email to the administrator is working correctly, but not the thank-you email:


texts:
I migrate my content from an old D7 site to D8 site. All went well, except the addresses from field address where not migrated to the new address field.

Then I use feeds, feeds_migrate, content-import... Nothing work for this.

Then finaly start learning how to do this in a custom module. I used the plugin from the module addres, I wrote my own plugin. No migration seems to work.

I have a CSV file with the addresses. There is also a NID row that is unique, I also try with the title field who also is unique. I try to import this csv file into my content type business. The nodes are existing with the NID numbers. Just try to fill the address in each content. All addresses are in Belgium.
Below my YML file in a custom module.

    id: migzaal
label: Adres veld migratie
source:
   plugin: csv
   path: modules/custom/adresmigratie/assets/adresinvoer.csv
   header_row_count: 1
   ids:
     - Nid
process:
   nid: Nid
   field_adres:
     plugin: addressfield
destination:
  plugin: 'entity:node'
  default_bundle: business
  overwrite_properties:
    - 'field_adres/address_line1'
    - 'field_adres/locality'
    - 'field_adres/postal_code'
    - 'field_adres/country'

Can someone guide me in the right direction. Thanks.


texts: How can I translate the checkout system?

texts:
I have been translating my Commerce Kickstart site with no ease although with success until now. Have translated content, taxonomy, product fields etc, following some tutorials and Drupal own documentation. Have installed a variety of modules for localization.

But now as regarding checkout system. I'm calling checkout system all screens starting by clicking on "checkout" in shopping cart block that appear in above and right corner of Kickstart demo store.

To translate checkout system, I went in https://localize.drupal.org/translate/downloads?project=commerce and downloaded my translation (Portuguese, Brazil). Then I imported that with /admin/config/regional/translate/import. In Overview tab all the 1222 expressions (100%) are translated. In Translate tab I searched for some strings that appear in that checkout system screens, like "Payment", "Checkout complete", and indeed there are already translations in Portuguese Brazil.

In /admin/config/regional/language/configure, on Detection and selection tab I enabled URL and Session as Detection methods.

So, are there more configurations that I need to do to have checkout system translated?


texts: Mapping a csv field to Meta Title and Meta Description using feeds and metatag

texts:
I have a csv of node data that I want to import into drupal. I'm using the feeds parse, and I can map the Page Title, Body, and other fields just fine. The issue I'm having is trying to map the CSV fields to the Meta Tag and Meta Description items (provided by the metatag module). Since metatag does not store it's information as a drupal field, I cannot map it with the feeds UI.

One possible solution I have considered is to use a metatag module that does use node fields to store meta data, but that would require a shift in the way our content editors handle things, and the installation of that seperate module on all of our maintained sites. I'd rather just use feeds with metatag

I'm a beginner when it comes to using the feeds api, and want to know if it is possible to write a custom mapping function that could populate metatag data for nodes from a feeds import.


texts: How do I add a block of JavaScript to the home page only?

texts:
I have a block of JavaScript I need to add to my homepage (and only my homepage) to enable the logging of clicks via a heat mapping service I signed up for.

They specified the code needed to be placed just before the </body> tag, but I imagine it's safe to put it anywhere within the <body> tag.

I'd like the snippet not to appear on any other pages. How can I accomplish this?

I am running Drupal 6.


texts: Do I need to create a database table or are there already tools on offer?

texts:
Pretty new to drupal, I'm afraid!

I have a excel table of survey results which I need to display certain cells from on a drupal page. I was thinking of creating a new table in my drupal database and then using PHP to link to it. I can't seem to create this table and what I've read suggests that this isn't a good way to go about it.

Does anyone know a better tool within drupal for this? Views or creating a custom module?

Thanks

Ed


texts: Delete an account without showing the confirmation form

texts:
I've been working on creating a feature which allows certain non-admin but higher-than-user roles within a Drupal 8.8 system to delete users from the system. In essence, only admin and 'moderator' accounts have access to the Drupal, and they need to all be able to 'cancel' a user account from a bulk action.
My problem is that despite setting all permissions correctly and according to the guides, the moderators are always given a choice to choose which cancellation method they wish to use on the account, and then need to confirm the deletion. This happens despite these accounts not having the permission to do so.
I simply want the system to, upon clicking on the action 'cancel this account,' to cancel and delete all the accounts without confirmation or anything else. Just click and go. I've tried implementing this using hooks, including hook_user_cancel_methods_alter as shown below by not giving administer rights and dropping that requirement, but nothing seems to work.
function clientname_user_cancel_methods_alter(&$methods) {
  unset($methods['user_cancel_delete']['access']);
}

Simply put: how can I skip the confirmation screen for a user cancellation/deletion in Drupal 8.8?


texts: Commerce, how to show 'view' of 100 products without speed/loading issues

texts:
I am attempting to work out my own delivery/collection slot setup.

Each delivery 'slot' is its own 'commerce product,' 10 x 1 hour slots per day for 10 days - 100 slots to span 10 days. Pick a slot and add it to the cart.

For the year I think there is around 4000 variants in one spreadsheet which i can import with feeds - so I have all the raw 'product data.'

Only thing is when I create a view of the 100 products it seems to get bogged down and takes ages to load - sorry for being non-technical.

Below is a screenshot of what I have and would like to achieve, how can I display my products as below but rapido!


texts: Entity Reference View fails after update to drupal 8.7.6

texts:
Recently I updated my drupal site from 8.6.14 to 8.7.6.

A previously-working Entity Reference View display that is connected to a form Autocomplete field stopped working.
The spinning circle keeps spinning and does not match user input to an entity.
(The ER View display concatenates a user email address and his company name for easier user selection : ie "joe@smith.com - Smith Plumbing, Inc." )

Error in log is:

  Error: Class 'Drupal\views\Plugin\EntityReferenceSelection\Xss' not found in Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection->stripAdminAndAnchorTagsFromResults() (line 272 of /Applications/MAMP/htdocs/chapter6/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php)

I added use Drupal\Components\Utility\XSS to ViewSelection.php and now the error is

  Recoverable fatal error: Object of class Drupal\views\ViewExecutable could not be converted to string in Drupal\Core\Entity\EntityAutocompleteMatcher->getMatches() (line 69 of /Applications/MAMP/htdocs/chapter6/core/lib/Drupal/Core/Entity/EntityAutocompleteMatcher.php)

Has anyone else experienced this in latest drupal 8?


texts: How to fix 'Call to undefined function node_load() in menu.inc' fatal PHP error?

texts:
Copied my live site to my local computer. From Windows server 2008 to Windows 7. Took a backup of the database via mysqldump. Restored the database on the dev-db-server.  Now I'm trying to get my local copy up-n-running. Browsing index.php gives me

Fatal error: Call to undefined function node_load() in C:\inetpub\wwwroot\my_drupal\includes\menu.inc on line 577

My hunch is that I have missed some web server settings allowing parent path or similar?

I have installed PHP and 5.3.13 and URL Rewriter via Web Platform Installer. According to CHANGELOG.TXT I'm running Drupal 7.0

However phpinfo(); works fine.

Edit / Update: I tried to narrow down the error. Following code fails on line 3. If I change the path on line 2 to something wrong the require_once will fail. Apparently IIS is able to find bootstrap.inc, but bootstrap.inc cannot find user_access()

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


texts: How to create custom bundle of "User" entity using GUI?

texts:
Is it possible to create custom bundle from "user" entity without programming? Only using drupal administration? Are there any modules that could help to create such bundles?

I would like to achieve, that some user roles would have custom fields. I have found this module for creating fields per user role, but maybe it would be better to create custom user bundle.


texts:
I am using jCarousel as below:

jcarousel_add('#jcarousel',
  array('vertical' => false, 'scroll' => 3, 'horizontalDirection' => $direction, 'initCallback' => 'slCarousel_initCallback')
);

How can I manually slide the carousel?

When I run jQuery("#jcarousel").jcarousel().next();, in Firebug I get the following:

>>> jQuery("#jcarousel").jcarousel().next();
[]

I have tried this as well in the Firebug console:

var carousel = jQuery("#jcarousel").data('jcarousel');
//alert (carousel);
carousel.next();

I got the following:

>>> var carousel = jQuery("#jcarousel").data('jcarousel'); carousel.next()
TypeError: carousel is undefined


texts: Creating custom button that gets a certain views block on the database

texts:
Is there a way to create a custom button that gets a certain views block on the database upon click?

I want to write a custom function button that upon click, connects to the database, retrieve a certain view block, and displays it in a .tpl page.

Thanks.


texts: programmatically add class name to fields

texts:
I want to add custom class name to fields in user login form other than default class name.
For example,

user-name-field for Username field
password-field for Password field
click-me-button for Submit button
creat-account-link for Create new account
request-password for Request new password

how to do this programmatically?


texts:
I created a simple view, it has 4 item (node) with 3 field (title, image, custom field).
The image, title and field_promote are null.

I tried this:

function theme_preprocess_views_view__customview(&$variables) {
   $rows = $variables['rows'];

   foreach ($rows[0]['#rows'] as $id => $row) {

        $variables['rows'][$id] = array();
        $variables['rows'][$id]['image'] = $row['#view']->field['image'];
        $variables['rows'][$id]['title'] = $row['#view']->field['title'];
        $variables['rows'][$id]['attributes'] = array();

        $variables['pager'][$id] = array();
        $variables['pager'][$id]['id'] = $id;
        $variables['pager'][$id]['content'] = $row['#view']->field['promote_title'];
    }
}


texts: Basic question with respect to Drupal form API

texts:
I am learning the Drupal Form API. I am new to HTML and PHP also.
I read in a book how to define a form in Drupal, where they used the following example:

/**
* Define a form.
*/
function formexample_nameform() {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
}

What will the HTML equivalent of above example be?
Similarly, to validate the form they did it as follows:

/**
 * Validate the form.
 */
function formexample_nameform_validate($form, &$form_state) {
  if ($form_state['values']['user_name'] == 'King Kong') {
    // We notify the form API that this field has failed validation.
    form_set_error('user_name',t('King Kong is not allowed to use this form.'));
  }
}

What will be HTML equivalent of both of these functions?


texts: How to format a date submission value of a webform?

texts:
I need to format a birthday submission value to the short format (01.01.2015) defined under admin/config/regional/date-time on a webform.

This Token is working but it uses the long format (Fr, 01/01/2015):

[submission:values:bday]

I tried the following token variations :

[submission:values:bday:short]
[submission:values:bday:custom:short]
[submission:values:bday:custom:d.m.Y]
[submission:values:bday:date:short]

But none of them submits my desired output. Any Ideas?


texts: Inclusion of SEO-related content in the header using structured Microdata

texts:
I am currently looking at the SEO of our site, and I will be using Schema.org Microdata in the head and 'rich snippets', as well as including Facebook OpenGraph data.

What is the best way to include this information in the header, extract it from the content etc.?

Are there any modules that can help out with this task? Are there any best practices?


texts: User error: "attributes" is an invalid render array key when rendering image

texts:
I'm seeing the following error on my Drupal 8.4.3 site:

  User error: "attributes" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

It happens when rendering a Paragraph that has a multi-value field in it, which uses the Responsive Image formatter.

The Twig template looks like this:

...
{% for item in items %}
  {% set original_image = item.content['#item'].getValue()['original_url'] %}
  <a href="#" target="_blank" rel="nofollow">
    {{ item }}
  </a>
{% endfor %}
....

The problem is on that middle line {{ item }}. It prints the error message once per item in the "items" array. According to the Twig debug output in the HTML source, the next inner Twig template should be core/themes/stable/templates/field/responsive-image-formatter.html.twig. For fun, I went into that template and deleted every line, leaving an empty file. And the error is still there. So it's happening somewhere between the outer template and the inner template.

When I put a step debugger on line 97, I see a variable $elements with the following structure:

[
'content' => ... render array stuff in here ...,
'attributes' => Drupal\Core\Template\Attribute[ storage => [] ],  // <-- what's this?
'#printed' => false,
'#cache' => ...,
'#attached' => []
]

It seems that the problem is that Drupal wants anything not starting with # to be a valid render array. Which the 'attributes' element isn't. But I can't figure out how that got in there. I don't think any of my custom code could generate something like "'storage' => []". I've been poring over the stack trace for hours and I can't tell where it's coming from.

Anyone know of a contribibuted or core module that could generate this? I would love to file an issue in the Drupal issue queue, but I can't even figure out which module is causing this.

System specs:

Drupal 8.4.3
Paragraphs 8.x-1.2 (the field in question is inside a Paragraph entity)
Multiversion 8.x-1.0-beta7 (in case that matters; it does change entity structure somewhat)
Image Lazyloader 8.x-1.0-alpha2 (I've seen this in the stack trace a few times)
PHP 7.0.26
Ubuntu 16.04


texts: Retrieving a field in a paragraph with JSON:API

texts:
I have a "user_group" paragraph type which has a user node reference field called "field_group".
Then each user has a paragraph reference field called "field_groups".
So, something like this:
User: field_groups -> paragraph reference with a field_group node reference
Now I need to retrieve all users that have a paragraph which references a given node. So I'm using this JSON:API request:
/jsonapi/user/user?filter[field_groups.field_group.id]={some-node-id}

But it doesn't return anything. I've also tried:
/jsonapi/user/user
?filter[group][condition][path]=field_groups.field_group.id
&filter[group][condition][value]={some-node-id}

Which also doesn't return anything.
Any idea on what I'm missing?
Update:
I've tried to retrieve paragraphs that reference the node directly:
/jsonapi/paragraph/user_group?filter[field_group.id]={some-node-id}

But this also didn't return anything... There's no error, but no data returned


texts: How to hide field from entity display view programmatically?

texts: I am adding field inside module.install file to specified entity. I want to hide this field from display. How can I do that?


texts: How to delete field programmitically using hook_update?

texts:
We have a situation where in different environments we have to manually delete fields. Rather than manually doing that, we want to programmatically deploy the changes. The idea that is being is discussed is to use a custom module which calls the hook_field_delete_instance() hook.

The issue we are having is how to best pass in the content type machine name and the machine name for a single content type. We are understanding that when we reused the field on a separate content type, we are essentially creating an alias on the current content type that points to the original content type holding the field name.

Using the situation below, what is the best way to delete the two fields on the on the basic page only using the hook_field_delete_instance() on a custom module?

Situation:

We have two content types: article and basic page. We created several fields on the article content type that we ended up reusing on the basic page.

Article:

field_art_original_publish_date
field_art_country_tag
field_art_image

Basic Page:

field_art_image (reused from article content type)
field_art_country_tag (reused from article content type)

Update:

So now that i am thinking further on this, i would like 1 hook update for 1 field deletion so that if a hook update fails then i know which fields need attention.

Here is what i have come up with using what @Clive has suggested.

function mymodule_update_7001(&$sandox) {
     mymodule_delete_field('field_art_image', 'page' );
}

function mymodule_update_7002(&$sandox) {
    mymodule_delete_field('field_art_country_tag', 'page');
}

function mymodule_delete_field($field_mn, $ct_mn) {
    $entity_type = "node";

    $field_instance = field_info_instances($entity_type, $field_mn, $ct_mn);
    field_delete_instance($field_instance);

    //setting the batch size to a large number resolves my prior issues
    $batch_size = 20000;
    field_purge_batch($batch_size);
}


texts: Exposed Node Title Filter is being applied when it shouldn't be

texts:
So this is a bit of a long shot but I wanted to see if anyone else has encountered this issue.

I've implemented a view that uses a custom base table that contains a relation to the node table. Some records on my custom table do not have an associated node id.

There is an exposed filter set for the Node Title so that the records can be filtered down to ones related to a specific node.

The problem I'm encountering is that records with no associated node id do not appear on the view. It's caused by the node title view filter inserting it's where clause despite not having any value to filter by.

Is there anyway around this problem?

For instance, can I implement a custom filter for the node title? The filter part is easy, but overriding the existing node field configuration seems more complicated.

Any insight would be greatly appreciated!


texts:
I have used default user login block on top navigation. I need to load another log in form on some pages.

I am trying to load the form by

drupal_get_form('user-login')

I get the following error:

  Notice: Undefined index: user-login in drupal_retrieve_form() (line
  763 of /path/to/drupal/includes/form.inc). Warning:
  call_user_func_array() expects parameter 1 to be a valid callback,
  function 'user-login' not found or invalid function name in
  drupal_retrieve_form() (line 798 of
  /path/to/drupal/includes/form.inc).

Is it possible to load a second log in form? (Drupal 7)


texts: Append html after node content in custom module in Drupal 7

texts:
I have an custom tpl.php inside of theme for some node type. It works fine but I would like my custom module to append some HTML after each such node (content of tpl.php). And I don't want to override the output from tpl.php inside of theme (just add something at the end of it).

Is there an hook for that or should I use different approach?


texts: Organic Group OG membership relationships

texts:
I'm trying to display on a views, only the nodes which the user is part of the Organic group.

I have a field og_group_ref in my content type which relate to a group.

What I want is for each user, display only the one he his part of. It seems relationship is the trick but somehow I can't make it work .

So far I tried in Relationship:

 OG membership: OG membership from Node group

(OG membership from node group) OG membership: User from OG    membership

and to add in contextual filter:

(user from OG membership) User: Uid (with default value set to "user id from logged in user")

But it doesn't seem to work!


texts: DB API: How to get a list of nodes ordered by highest comment creation date?

texts:
The DB API is once again kicking my tail...

I've got a bunch of nodes of a certain type, each of which can have any number of comments, all in the usual way.  I'm trying to do a db_select()-based query that will give me the set of nodes of that type, ordered by the creation dates of each node's comments: The first node in the set would be the one that has the most recent comment, the second node would be the one that has the second most recent comment, and so on.  I'm sure / strongly suspect that this takes some sort of subquery, but I'm just not getting it right.  Can anyone offer some help?  Thanks!


texts: Implement hook_token_info and hook_tokens

texts:
I am trying to create custom tokens, but my implementation doesn't work.
I have implemented hook_token_info() and hook_tokens() like this in my .theme file for Drupal 7.

/**
* Implements hook_token_info().
*/
function THEMENAME_token_info() {
  $info = array();

  $info['types'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'name' => t('Commerce Order Billing'),
      'description' => t('Global commerce order billing tokens'),
     ),
  );
  $info['tokens'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'address-info' => array(
        'name' => t('Commerce address information'),
        'description' => t('Token for commerce address information'),
      ),
    ),
  );
  return $info;
}

/**
*
* Implements hook_tokens().
*/
function THEMENAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'commerce-order:commerce-customer-billing') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
      case 'address-info':
        $address_info = theme('nr_commerce_address_information', array('order' => $order));
        $replacements[$original] = $address_info;
        break;
      }
    }
  }
}

When I see the list of available tokens in the interface, my tokens does not show up. Why? Is there anything wrong in my code, or is the reason another one?


texts: How to make my blocks switch to another block when session was set?

texts: I have 2 header block, default 1 is the login form and the other block was for logout button. I want to make this two blocks switching after triggering the login button


texts: Can I create a keyword filter on emails sent from an email form with Rules?

texts:
Can I make a Rule that will check content of an email sent from a contact form and block the send if a condition is met?

I was hoping I could set up a Rule to react on event Before Email Send, or something of that kind and then check the content, but that event doesn't exist: could I create it? Or is there a better way?

Context: I have a content type where each node is an advert for a local attraction. I have an email field which is set to display as an email contact form which can be submitted by anonymous users.  I am using Mail System and Mandrill to send the emails.

Although I have Spamicide module and Captcha already installed, the odd spam email is creeping through the form.  The spams are usually highly obvious and would be simple to eliminate if I could set up a keyword blacklist, but I am not sure how best to create one.


texts:
I have a hosting with suPHP handler which doesn't support opcache. I want to start working on Drupal 8 sites which highly recommend opcache.

Is there any alternative to opcache? Should I change my hosting?


texts: I have just installed the Newsletter module, and I am wondering if it is possible to allow users to click on a "subscribe" button, and have them signup for a newsletter, rather than have an administrator manually add subscribers.


texts:
I was doing some work on my custom module which hooks into and modifies Drupal Commerce, and all of a sudden the checkout page wont load and I get this error:

Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /var/www/test.dev/htdocs/includes/entity.inc).
EntityMalformedException: Missing bundle property on entity of type commerce_customer_profile. in entity_extract_ids() (line 7693 of /var/www/test.dev/htdocs/includes/common.inc).

and I have no idea how to fix it! I commented out what I had changed and nothing worked. I even did a git stash on all of my work to revert the changes and still nothing. My only guess is that somehow the database got messed up. How can I fix this? If I have to mess with the database, where do I start?


texts: Modifying behavior of "You Saved..." info in cart when attributes are chosen

texts:
I'd like to modify/eliminate the "you saved" text/info on the Cart page when a certain attribute (or attributes) has been chosen for the product in the cart.

This is the code from uc_cart.module that appears to handle the "you saved" info:

      $totalfield = '
'.uc_price($display_item['#total'], $context).'
';
  if ($item->list_price > $item->price) {
    $savings = $item->list_price - $item->price;
    $savings = $savings * $item->qty;
    $totalsavings += $savings;
    $totalfield .= '
You saved '.uc_price($savings, $context).'!
';
  }

And I'd like to add something like "Do not display the 'You Saved' div if Option X, Option Y, or Option Z have been chosen".

Can anyone here direct me on how to accomplish that? Or could a jquery snippet such as this provide the same "hide" functionality?

(function($) {
 $(document).ready(function(){
if ($('.item-list > li:contains("sometexthere")').length > 0) {
    $(".cart-savings").addClass("newclass");
}
});
 })(jQuery);

The "newclass" would have a CSS display:none property that would hide the cart-savings div if the item-list (attribute options listing) div contained one of the words that is only used in these options. Or, it could be flip-flopped, where the div is already hidden via CSS, and the jquery adds a new css class that unhides it via "display:block".

Thanks!


texts: How to force a JavaScript library to load in the  of a Drupal 8 page

texts:
How do I force a JavaScript library to load in the < head > in Drupal 8?

Here's my themename.libraries.yml file:

zaccordion:
  version: 1.x
  js:
    js/jquery.zaccordion.js: { header: true }
    js/jquery.zaccordion.min.js: { header: true }
    js/zaccordionUsage.js: { header: true }
  dependencies:
    - core/jquery

It still loads in the footer however.


texts:
I want to send a HTML email from rules but I cannot get it correct.

Installed mime, html, mail. Created rule. only a trigger and action send html email.
In the rule: no message key defined, subject is something like [node:nid], body is [node:body]

Made a template at campain monitor, now i have foo.html. Renamed foo.html to mimemail-message.tpl.php in default theme directory and put [node:id] and [node:body] on the correct place. Soo, the css is in the tpl file.

1) When testing I get an html email (logo is visible) but no colors.
Installed and configured: sites/all/libraries/emogrifier/emogrifier.php
Mailsystem is using mime, mime is using full html filter including emogrifier.
No change in the result.
I read the message with gmail. Adblockes disabled.

Any suggestion what to do ?

2) How to get replacement of the tokens. Which tokens are available for this tpl file?


texts: How to hook contact form of drupal 7 for custom styling?

texts:
how can I alter my contact form for adding custom classes
I am using contact form of Drupal 7 core module.


texts: Combined PHP and HTML in nodes and blocks

texts:
I'm trying to find a way to translate blocks in a Drupal 7 site using PHP and HTML coding.
Now, my blocks in the current language of the site are written in HTML, but I am wondering if I could include a PHP script, using PHP code format in the block, in order to switch content if the language changes.

In general, is there a way that I could combine HTML and PHP code in a node/block/custom text?

I recently wrote PHP code in the header of a view (using the PHP code format), in order to print a message if the user is not logged in, but when I added HTML in it or before it, it stopped being displayed.


texts: Cloned Seven/Bartik themes don't show up

texts:
I copied bartik and seven theme from core/theme folder into the /theme folder.

I renamed both into xbartik and xseven.
I renamed all the files named bartik to xbartik and seven to xseven.
I did a find a replace in the info and theme files to the corresponding name change of xbartik and xseven.
Did a flush cache and it doesnt show up.

What else could I be missing in this process?


texts:
I am doing theming of user edit profile page

Now i have three fields here

Password, currentpassword, confirm password

What are their field items

i have tried

    <?php print render($user_profile['account']['pass']['pass1']); ?>
<?php print render($user_profile['account']['pass']['pass2']);

Which is not working

Also i am not sure about third filed

Anybody can tell me

Thanks


texts:
Been reading a lot of questions and playing around alot and I haven't been able to figure this out.

I have a node with a field for entity references.  I'm trying to make a view that I can put on the node page that will grab the fields I want from the referenced entities but I haven't been able to make this happen.

I've created a view that that gets the current NID and I've set up relationships to the entity reference field on the node.  I've also created a node with a the reference field filled out and in the views preview I'm passing that NID, but nothing is returned.

Does anyone have an idea why the view isn't returning the referenced entities that I've defined on the specific node?

Thanks,
Paul


texts: Get array length of a multiple fields of a node content type

texts:
I'm developing a site with Drupal 8. I made a custom content type, with a lot of fields; in particular I have a field called field_categoria_del_libro_presen that is linked to a taxonomy term. It's possible to specify more than one value. I used kint() to obtain the structure of the node. Here:

field_categoria_del_libro_presen
→array(2) target_id
  1
    "1"
  2
    "4"

how can I get the length of the array?


texts: How can I achieve taxonomy workflow (allowed next states of taxonomy terms)?

texts:
I have a vocabulary containing some terms for issues' states:

Open
In progress
Closed

I want to be able to define allowed "next" states for each term. So that a user can only change:

Open -> In progress
In progress -> Open, or Closed
Closed -> None

I am using Drupal 7.


texts:
So I'm trying to do something really simple but haven't manage to know how to do it with the Ajax API form from drupal 7. I have an administrative GUI with a select input type, I set the #ajax property with the callback but I don't want to replace anything just need to reload/refresh the values for specific inputs most of them textfield, when the selection change.

Any insight on how to do this? Can it be done with the Ajax Drupal 7 API?

Thanks....


texts: How can I alter the breadcrumbs on a search page?

texts:
I just enabled search on my Drupal theme and when I go to the search page my breadcrumbs show like this:

  home > Search > Content > Search

Is there any way to make it just:

  Home > Search

Thanks!


texts: Filter the users name in the list of admin / people of organic groups Drupal 7

texts:
I have a lot of users in several organic groups, I need filter the users by username to acept or deny join to group.

Generic url group page: group/node/[nid]/admin/people

I appreciate any guidance to filter users (contributed module, hook_form_alter...) or disable pagination in this page.

Thanks :)


texts: How to programmatically require a field using Inline Entity Form

texts:
I have a node form using an inline entity form widget for either selecting or creating taxonomy terms to be referenced from the node.  The field should be required at a certain moderation state, but in the early stages of moderation the field does not need to be required.  I'm trying to make this change in hook_form_alter
I tried comparing the values of $form in the alter function when the field had been set to required, and when it hadn't.  The only differences were within $form['field_name']['widget']:
$form['field_name']['widget']['#required'] => 0
vs.
$form['field_name']['widget']['#required'] => 1
and
$form['field_name']['widget'][#element_validate] => Array
                (
                    [0] => Array
                        (
                            [0] => Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex
                            [1] => updateRowWeights
                        )

                )

vs.
$form['field_name']['widget'][#element_validate] => Array
                (
                    [0] => Array
                        (
                            [0] => Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex
                            [1] => updateRowWeights
                        )

                    [1] => Array
                        (
                            [0] => Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex
                            [1] => requiredField
                        )

                )

Just adding $form["field_name"]["widget"]["#required"] = TRUE; to the alter didn't change anything, and trying to add the #element_validate bit lead to an error:

User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

How can I programmatically require an inline entity form field in a hook form alter?


texts:
I'm working on my custom module that has a form having an email field and I'm using drupal 8's ajax form validation to validate the email whether it exists in the database already or not. But the problem is even if it finds the entered email in the database and throws error but it submits the form as well. This is happening in the ajax validation which i am triggering on forms submit click. If I remove the ajax validation and do the validation like normal, it works perfect.
Using Drupal 8.2.6

Question is why it's submitting the form on ajax validation? It found the email is duplicate shows the error then it should not submit the form. Why is it happening? Can anyone help?

$form['actions']['submit'] = array(
  '#type'=>'submit',
  '#value'=>'Subscribe',
  '#attributes'=>array(
    'class'=>['button--primary']
    ),
  '#ajax'=>array(
    'callback'=>array($this, 'ajaxValidateEmail'),
    'event'=>'click'
    ),
  '#suffix'=>'

',
  );

And here is the ajaxValidateEmail itself.

public function ajaxValidateEmail(array &$form, FormStateInterface $form_state) {
$email = $form_state->getValue('email');
$table = 'subscribe_subscribers';
$query = db_select($table, 'subscriber')
        ->fields('subscriber')
        ->condition('email',$email,'=')
        ->condition('status',1)
        ->execute()
        ->fetchAssoc();
if ($query) {
  $response = new AjaxResponse();
  $response->addCommand(new HtmlCommand('.email-error-message', $this->t('Email already exists.')));
  return $response;
 }
}


texts: How do I parse application/vnd.surveymonkey.response.v1+json?

texts:
I recently asked a question about setting up SurveyMonkey webhooks here: https://drupal.stackexchange.com/questions/252571/surveymonkey-v3-webhook-callback

After laborious troubleshooting, I've determined that the issue is that I need to be able to parse the request as application/vnd.surveymonkey.response.v1+json.

How do I do that?

There's no option to add this type of parser, or a custom parser, in the REST server config. Googling for a few hours has come up with nothing. In a Drupal REST endpoint, how can I use this parser type?


texts: Order of drush commands for automated deployment?

texts:
What order should the following drush commands be ran?

config-import
updatedb
entity-updates

Also, I see entity-updates fail a lot due to field_delete_data* tables existing. How can I delete them as part of my automated deployment?


texts: How are the default search results are sorted on D7?

texts: I have a basic search configured on my site. I wanted to know how is the default search results are sorted in drupal, is it by the number of words found on the content or based on date the content is created or something else. I know it can be altered using custom modules. But I am curious to know how default on works.


texts: How can I show all translations of a field in a node

texts:
I am working on a relatively simple multilingual site. I only need to translate the title of each node, so I thought a lightweight approach through entity translation and the title modules would be the best way to go.

I want to show the original title as well as its translation in the same node, and let users choose which language they want it translated into through a dropdown selector (not the language switcher block as I don't need different URLS or the whole page translated)

I am trying to do this through a views block, providing the node id as an argument and the language selector as an exposed filter. But I can't get my head around it so far: the node title in the block is always the original one (english).

Any thoughts, different approaches, tips, code, module suggestions will be most appreciated.

Thanks in advance


texts:
I use the Drupal Core IP blocking feature (/admin/config/people/ip-blocking) to block IP addresses during spam attacks. However, as most of these will be dynamic ones owned by legitimate users a day later, I want to remove these blocks.

I could delete them one by one in the IP blocking interface, but with dozens of addresses, that is not a comfortable way. Any alternative?


texts: Why is Views ignoring nid as second argument?

texts:
I create a view with two arguments: Taxonomy ID (tid) and Node NID (nid). I leave the default settings for tid and set a default argument for nid to a fixed value (let's say: 1). The tid argument is configured so that all values are shown in case it is not present. This should show all nodes except the one with NID 1.

BUT: This only works if the NID argument is the first argument. If it's the second argument, it is excluded from the query:

Query with nid as first argument:

SELECT node.nid AS nid
FROM node node
WHERE node.nid != 1  OR node.nid IS NULL

Query with nid as second argument:

SELECT node.nid AS nid
FROM node node

I'm wondering why that is? What I want to accomplish is actually to exclude the result of one view from another. To do that, I add nid as an argument, get the nids of a different view and tell views to exclude them. That works just fine, but only if nid is the first argument. But I need to have taxonomy as the first argument and I don't understand why that excludes my nid argument.

Although in a different context, I think I had the same problem here:
https://stackoverflow.com/questions/20248929/filter-a-drupal-view-displayed-in-a-panel-by-taxonomy-term-depending-on-domain


texts: Make the order available in checkout pane callback when viewing

texts:
I've overridden the payment pane callback in the checkout page (using hook_checkout_pane_alter), and I want to modify the form inputs in the pane based on the order total. However, the order object is empty when the callback is called with the "view" operation parameter.

How do I make the order available in the callback function?


texts: I used the CCK module to create a content type that has three fields (title, description, and body). I want to overwrite two pages: one is where there is a "create content" navigation located on the left page; the other one is where I click  on "Create page" and which displays the form page.


texts: Couldn't create a subtheme of a core theme

texts:
I want to do some customization on seven administation theme, I won't to copy it in my themes folder, I want to create a subtheme of it, it doesn't work for me. this is my info file

name = SEVEN SUB
description = a Seven subtheme
base theme = seven
core = 7.x
stylesheets[all][] = style.css

when I replace Seven by a theme already exists in my sites/all/themes, my theme inherits it, but for core themes it doesn't.
I tried to specify the path of seven, themes/seven and /themes/seven doesn't fix the problem.


texts:
I have enabled "View all products product" -- I have disabled sql rewriting.

Although I still cannot get anonymous users to VIEW ANYTHING in the store. Because of the ADMIN overlay?


texts: How to load entity by UUID from url argument?

texts:
Usually routes have the {entity_type} argument in their path and Drupal loads the entity by the ID that is the url argument. For example route defining /node/{node} would work with /node/5.

I need to load the entity not by it's ID but rather UUID. So the path would look like /node/0ff3b31b-5abb-4377-bb00-af71882e38a4

Is it possible to load the entity by UUID by defining some sort of mapping in the route definition or do I have to create my own ParamConverter for this?


texts:
Getting the following error after switching servers. The setup is multisite on a linux box. The troublemaker is on subdomain.
So far:
disabled quiz and quiz submodules,
cleared the cache, nothing really works.

Fatal error: Call to undefined function quiz_type_access_load() in /path/to/drupal/includes/menu.inc on line 411


texts: Outputting FPDF to a new tab with form ajax

texts:
I have a custom form with text and number fields, saved with a Submit button. In this form, I also have another button which outputs the form data to a PDF (without submitting it).

The code for the pdf button is as follows:

$form['wrapper']['pdf'] = [
    '#type' => 'submit',
    '#name' => 'makepdf',
    '#value' => t('View pdf'),
    '#submit' => array(array($this, 'generatepdf')),
];

My generatepdf() ajax function processes the form data and outputs it to a PDF.

I am using the FPDF, FPDI, and TCPDF libraries to create this PDF. There are only four output options for the completed PDF, and one of them simply loads the PDF in the current tab. There is no native option to output to a new tab.

I understand that there are a variety of workarounds to accomplish this: the FPDF documentation states to "add a target="_blank" to your link or form." This would be fine, but the button creating the PDF is not a link, and adding it to the form would also make the save/submit button open a new tab which I do not want.

I have also tried to change the button calling the PDF generator to an HTML tag of type "a":

$form['wrapper']['pdf'] = [
    '#type' => 'html_tag',
    '#tag' => 'a',
    '#value' => $this->t('View pdf'),
    '#attributes' => ['target' => '_blank'],
    '#ajax' => array(
        'event' => 'click',
        'callback' => array($this, 'generatepdf')
    )
];

but the #ajax attribute does not seem to do anything for this type of form element, nothing happens when I click it.

I have also tried changing it to a Link form element:

$form['wrapper']['pdf'] = [
    '#type' => 'link',
    '#url' => null,
    '#title' => $this->t('View pdf'),
    '#attributes' => ['target' => '_blank'],
    '#ajax' => array(
        'event' => 'click',
        'callback' => array($this, 'generatepdf'),
    )
];

but the link never renders, it is nowhere to be found in the form or in the page inspector.

Is this possible to accomplish using Ajax in drupal forms?

EDIT: I got the Link element to at least show up and show an ajax spinner when clicked:

$form['wrapper']['pdf'] = [
    '#type' => 'link',
    '#url' => Url::fromUserInput('#'),
    '#title' => $this->t('View pdf'),
    '#attributes' => ['target' => '_blank'],
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'generatepdf'
    )
];

When I click on it, the spinner shows, but disappears after a second. Nothing else happens. The generatepdf function is never fired. I even added ddl(true); to the start of the generatepdf() function to see if it is firing, and nothing shows up in the ddl logs.


texts: Menu does not appear while viewing a node of a particular content type

texts:
I've a singular problem.

On my installation I've several content types and I've a menu that appears on every page.
The problem is that on every node of a certain content type (and ONLY with nodes of this content type) the menu isn't displayed.

This happens if I set the block with the default way to place blocks and also if I try to place it with context.

I've tried also to add on the page.tpl.php this code:

$menu = menu_navigation_links("menu-name-here");
print theme('links', $menu);

Links from "menu-name-here" are printed on EVERY page, but are not printed in nodes of one content type.
I've not tpl for nodes..

It seems that on this page functions to get links from menu don't works: any ideas?

Thanks


texts:
So I have setup a View as a Block that echoes out three products from Commerce. However I want each of the items to be formatted in this way:

PRODUCT PRICE

PRODUCT DESCRIPTION

Donate Now >

Is it possible to edit the formatting specifically in this way?

Thanks for your time!


texts: SQL + Drupal: how to filter correctly using SQL within a Drupal Database?

texts:
I have been using Drupal for quite sometime, but now I have come to a crossroad: using MySQL to extract data from my site's database via phpMyAdmin.

Everything was going great with the basics (I was going through w3school's tutorials), I learned a lot about SELECT, operators, booleans, etc., but then I came to a stop while trying to filter my results concerning dates, with UNIX TIMESTAMP.

I need to be able to filter results between two dates and, no matter what I do or try, my results are wrong.

I have been trying to wrap my head around this concept (which I believe I already have) but I haven't been able to filter correctly using timestamps.

I went back to square 1 to review syntax, so I want to think that's not my problem, but I definitely need help.

Has anyone found something in the web that might cover this issue? Everytime I look for UNIX TIMESTAMP articles, they are quite superficial (I guess this is not a very hard issue after all).

Thanks in advance.


texts: Select List, 'Other" option text field, any text written in textfield 'Illegal Value' error is given

texts:
In one of my content types, I have an option for a select list with pre-defined values. I have the 'other' field configured, so when selected a text field displays to enter the 'other' information.

However whenever a user enters information into the text field and attempts to save the form, an "Illegal Value" error is displayed.

I went in and looked at the configuration and could not see anything wrong. Any ideas?


texts:
Where to tidy up field values before they are outputted to twig in D8?

hook_theme?
hook_preprocess_field?
twig extension?
field formatter?


texts: How do I filter a view based on a multilingual alias?

texts:
I have a view with a contextual filter which builds a page based on a product's model number. The path is /support/%, where % is the contextual filter for the model number.
This works fine for English content. I would like additionally take a path of /assistance/% for French content. How can I have one view with two, or variable paths?


texts:
I'm looking for a way to only show elements related to a specific day in the week. Let's assume that the url to the view is: /program/schedule. What I would like is that when you go to: /program/schedule/monday,  only the info related to the monday is displayed.

Now I already figured out the contextual filters and that I can limit the valid values to: monday, tuesday, wednesday, et cetera. This is not the problem. The problem that I'm having is that it seems that my date time field needs to have an input of a specific date like 20130902.

I also need to point out that I am able to format my date time field to only show as a day of the week (with date formatting), but this does not seem to impact the contextual filter.

Is there a way to achieve this? Maybe with hooks or something custom?


texts: When exporting a Feature, how can I turn off all page cache related settings?

texts:
I’m trying to export a Feature that would be used in a typical development environment. I want to have anything related to page caching turned off. But on the create feature page I’m not seeing where to do this. I would have thought there would be a Strongarm variable that reads Cache pages for anonymous users but there isn’t one. Also looking for the same for ‘Aggregate and compress CSS files’ and ‘Aggregate JavaScript files’.

So to clarify, how can I export the following in a Feature?

Cache pages for anonymous users -> OFF

Aggregate and compress CSS files -> OFF

Aggregate JavaScript files -> OFF


texts:
I've been using Drupal for several years, but only just dipping a toe in with Drush - I've bought an ebook tutorial and working my way through. I've installed Composer, and used it to install Drush. The tutorial book specified a particular build of Drush to install (7.0.0-alpha5). I've navigated to a drupal folder and run

drush st

to get installation info which works fine.
The tutorial explains that you don't have to navigate into the drupal folder to do this, instead using

drush --root=PATH-TO-DRUPAL-SITE st

however this brings an error:

Fatal error: Call to undefined function conf_path()

Googling this error suggests this a problem with the version of Drush and to upgrade.

SO I've navigated into the .composer/vendor/drush/drush folder and run
    composer global update
but composer says nothing to update, confirming the version as 7.0.0-alpha5 - I assume this is not the latest 7.x version, so do I need something changing in the composer.json file?


texts:
In drupal 8 how can I hide title on front page ? The title is rendered through page-title.html.twig through the code below

{% if title %}
  <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
{% endif %}

I want to wrap it in if not front page condition but don't know the syntax.


texts: Create a zip file from a list of selected files and make the zipped file downloadable

texts:
I have a list of image files. I need to archive those files in zip format and make the archived file downloadable. I have seen ArchiverZip class defined in the system module of Drupal 7. But I couldn't be able to create a zip file. How can I do this in Drupal 7 ? Is there any hooks or custom modules for this ? Please help me out with this.

UPDATED
Following are the codes:

$zip = new ArchiverZip('archive.zip');
foreach($_POST['img'] as $fid):
    $query = db_select('file_managed', 'fn')
            ->condition('fid', $fid)
            ->fields('fn', array('filename'));
    $result = $query->execute();

    foreach($result as $row) {
        if(file_exists('sites/default/files/'.$row->filename)){
            var_dump($zip->add($base_path.'sites/default/files/'.$row->filename));
        }
    }
 endforeach;

And this reflects the following error

  Exception: Cannot open archive.zip in *ArchiverZip->__construct()* (line 91 of basepath\modules\system\system.archiver.inc).

Please help me with this . .


texts: Passing Node ID/Title to Next Page Webform Field

texts: I am new to drupal 8 and assisting my development team with design part. We are stuck in one place and not manage to move forward. We want to pass the node ID info to a webform filed which exist in another page. In the attached image I have explained what we want to achieve in Drupal 8 Environment, previously with PHP hack it was possible in drupal 7 but no idea how to achieve the same in drupal 8.


texts:
I am trying to show a user profile field in node form.

function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id){
        $form['myfield'] = array(
            '#markup' => drupal_render(field_view_field('user', $account, 'field_myfield'));
        );
}

field_view_field() is not returning any thing.


texts: Why are values in Entites obtained directly and sometimes by using getters?

texts:
For example

Drupal\Core\Entity\Entity::id() returns $this->id(or NULL)
Drupal\Core\Entity\ContentEntityBase::id() returns $this->id->value
Drupal\Core\Entity\ContentEntityBase::uuid() returns $this->get('uuid')->value
Drupal\node\Entity\Node::id() returns $this->get('nid')->value

Also in some methods there are setValue() and getValue() utilised but sometimes there are just $this->field->value.
So what is the reason for this inconsistent behavior? From my understanding all the "fields" are TypedData fields hence the setValue() and getValue() methods should be used instead of directly access $this->field->value. Besides it's strange because $value is private.


texts: How do I create an entity reference from a webform submission?

texts:
I have two content types : Parents and students. each content type has a entity reference to the other content type. I am using module : webform and webform creator to create the content.

Once a parent is login s/he can add a student by calling the student form.
After filling up the student form and submitting it the parent is redirected to the parent page which should show the student(s) just created.

How can I create the relation parent-student (one to many) so that each added student show on the page of the parent that created him/her once the webform is submitted or just by going to a parent page ?

Do I use token or how can I programmatically create the relation on webform submit?

Note: I tried unsuccessfully using the entity select in webform to link the student to parent since it is the current user (the creator of student). The entity reference generated is anonymous instead of the parent (the creator of student).


texts: How can I get the real password via hook_user_update()?

texts:
I want to change the current user password, and get the new password(the real password, not md5 encryption) when edit the account profile via user profile form(e.g.: example.com/user/1/edit) and save. would anyone can tell me how to do that? I tried using hook_user_update(), but it didn't succeed.

I mean I want to change the current user password, and I want to get the new password.


texts: How to automatically link specific words in a node to other nodes?

texts:
Lets say i have a node with a body like:

"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc cursus dapibus diam sit amet aliquet.
"

I'm looking for a way to convert the consectetur (for example) word into a link to another node, when the node is displayed (and not when is edited!)

What is the best practices to define what node shuld be linked to that word (taxonomy? cck field?), and how to do that (theme_preprocess_node?).

Please note that, whatever hook/theme function i can use, the results must be cached (until the node get edited again): the site is for a no-profit cultural association with the lowest budget i've ever seen ;)


texts: Attempt URL alias for spanish version of page - "The path */* is either invalid or you do not have access to it."

texts:
Drupal 7.59. We have the page whatever.tld/thanks and whatever.tld/es/thanks.
I'm trying to setup whatver.tlp/gracias as a URL alias for es/thanks and it says "The path 'es/thanks' is either invalid or you do not have access to it."

The page itself is a tpl.php file referred to by a view and has individual blocks on it that are translated.

This translation stuff is beyond me. I have a dev site to practice on so I'm happy to try out any ideas. The following (apparently) applicable modules are enabled:

GTranslate
Block languages
Internationalization
Menu translation
Multilingual content
String translation
Translation sets


texts: Filter by taxonymy ID with multiple field in contextual filter

texts:
In drupal 8.9 I need to filter by taxonomy ID over multiple fields in the contextual filter of views.
How to do this ?


texts:
I get this error on my site

  Drupal\Core\Extension\Exception\UnknownExtensionException: The module
  does not exist or is not installed. in
  Drupal\Core\Extension\ExtensionList->getExtensionInfo() (line 346 of
  ...core/lib/Drupal/Core/Extension/ExtensionList.php).

This error is happening in shared hosting server.

  public function getExtensionInfo($extension_name) {
$all_info = $this->getAllInstalledInfo();
if (isset($all_info[$extension_name])) {
  return $all_info[$extension_name];
}
throw new UnknownExtensionException("The {$this->type} $extension_name does not exist or is not installed."); // line 346

}

I have been searching online and found lot of discussions but I could not fix it. How can I fix the error?

Php: 7.0
Drupal: 8


texts: Difference between create new and edit node in form alter

texts:
I have an alter section for a particular content type. In the form alter how can I find out whether it is create new form or edit form?

With dsm($form) in from alter I can get results with several differences between them. What is the best way to distinguish those from each other?

is this a good way?

    if(isset($form['nid']['#value']))
     'means in edit form'
    else
     'means in create new from'


texts: Keeping $attributes but adding a rel (D7)

texts:
I have the following piece of code:

l('

' . $image, $link_path, array('html' => TRUE, 'attributes' => $attributes))

Which creates a nice link, as it should be. Now I want to add a rel-attribute without getting rid off $attributes (because I need that one). I have Googled and tried a lot, but nothing seems to work. So if anyone can help me with just adding a rel-attribute without deleting the other attributes, I would be grateful!

Thanks


texts: How to style/theme an openlayers map block?

texts:
I can't seem to figure out how to target the block that my OpenLayers map sits in. I've switched from a Gmap to an OpenLayers implementation, so I already know which styles I want to apply to the Map block itself, but when I mess with the styles in chromes dev tools I get strange results such that my points and map controls get moved, but not the map container itself

So applying the styling to the map block directly in dev tools result in the base-layer being pushed off and inaccurate. It looks like the map block and div id's get generated by the javascript in openlayers on each page load, so I'm not sure exactly how or where to apply my CSS. I get similar results when I target the map container div as well.

This the css I was applying to the Gmap

#block-views-phi-rho-chapter-map-block-1 {
  width: 95%;
  margin-left: auto;
  margin-right: auto;
}
@media all and (min-width: 720px) {
  #block-views-phi-rho-chapter-map-block-1 {
    width: 85%;
  }
}
    .view-phi-rho-chapter-map {
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  border: 10px solid #dbdbdb;
}


texts: Is it possible to override a core function instead of just altering it?

texts:
I would like to add a feature to the core string contextual filter, implemented in core/modules/views/src/Plugin/views/argument/StringArgument.php.

If I use hook_views_query_alter(), I would have to undo everything the core function did first, then roll out my changes.

Is there a way to just completely override the core function instead of only altering the results?

The contextual range filter accomplishes this by presenting the site admin with a configuration page to select which instances of an existing filter should be replaced by the new object. I could follow this route, but I would prefer to update all cases site-wide.


texts:
the following code to replace the displayed name of the subtotal.

How to change the display name of order total ?

// Rename subtotal.
function seven_subtheme_back_office_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Sous-total hors remises');
}

the following code does not work, it must be poorly written :

// Rename subtotal.
function seven_subtheme_back_office_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Sous-total hors remises');
  $components['commerce_price_formatted_amount']['title'] = t('ORDERrrrr TOTAL');
}


texts: How to display nodes in a view, each row using a preselected view mode ?

texts:
I would like to create a view that displays a number of nodes, each using its own chosen view mode.

I've installed the Display Suite module and created a number of view modes. Using the Views module, I've created a view that displays a number of entities/nodes and I can set a view mode for each row, or a default view mode for all rows.

However, I would like the view to somehow use the view mode that has been selected when creating the content itself (under the display settings tab).

So far I have no idea how to achieve this. Could anyone give me some pointers?


texts: Building form and saving as a content type

texts:
I have designed a site. In this site there is a content type for our experts. Also we need to design a form to employ more experts. We need people send form and admin see their forms, edit and then publish as our content type. Problem is, webform is not suitable for this. Is it possible using CCK as a webform? Is there another solution for this? Is it possible saving webform as a content type?

Thank You


texts: form_state['values'] generating error undefined index: values

texts:
I am having a simple form like this. I want to read the ID value in the middle of the form. When I try to get it using $fromvalues = $form_state['values']['id']; it gives the following error:

  Undefined Index: values in templates_form()

function templates_form_add($form, &$form_state, $templates = NULL) {
  $templates = entity_get_controller('templates')->create();
  return templates_form($form, $form_state, $templates);
 }

 function templates_form($form, &$form_state, $templates) {
   $form = array();

   $form['id'] = array(
     '#title' => t('ID'),
     '#type' => 'textfield',
     '#default_value' => isset($templates->id) ? $templates->id : '',
     '#description' => t('Unique Id'),
     '#required' => TRUE,
     '#maxlength' => 255,
     '#disabled'=> empty($ntemplates->id) ? FALSE : TRUE,
   );

   $fromvalues= $form_state['values'];

   $form['city'] = array(
     '#title' => t('city'),
     '#type' => 'select',
     '#options' => $cities,
     '#default_value' => isset($templates->city) ? $templates->city: '',
     '#required' => TRUE,
     '#maxlength' => 255,
     '#disabled'=> empty($templates->id) ? FALSE : TRUE,

   ),


texts:
I'm using Drupal 7 with views 3.

I am listing the student fees in a view and one of the field in view results is pid (payment id) which has some numeric value or NULL value. The NULL value means the payment is unpaid. I have used a custom field handler to show in view result as paid and unpaid for pid = some value as Paid and pid = Null value as Unpaid.

I want a filter on this field also which will have a drop down of two options as paid and unpaid. Which views filter I should use and how can I rename the drop down options?

hook_views_data()

// Status of payment paid or unpaid if pid is null in joined result set : unpaid
    $data['fee_schedule_payments']['payment_status'] = array(
        'real field' => 'pid',
        'title' => t('Fee schedule payment status'),
        'label' => t('Status'),
        'help' => t('Fee schedule payment status'),
        'field' => array(
      'handler' => 'fee_management_handler_field_payment_status',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_WHICH_ONE_I_SHOULD_USE',
    ),
    );

class fee_management_handler_field_payment_status extends views_handler_field {
    function construct() {
    parent::construct();
    $this->additional_fields['pid'] = 'pid';
  }
  function render($values) {
    $pid = $this->get_value($values, 'pid');
    if (!empty($pid)) {
            return 'Paid';
        }
        return 'Unpaid';
  }
};

Thanks in advance for your help.


texts:
Is there any solution yet which allows me to upload multiple media entities at once? At the moment I've to

Select a file
Upload it
Select the next file
Upload this

Especially for a gallery, where I've to upload a lot of images, this can be very annoying.

I really like to use the media entity module for this job because this way I can reuse all the images I've already uploaded in my gallery for other content.


texts: How to automatically skip intermediate redirects?

texts:
I've run into the issue where I end up with something like this:

about-us01 --> about-us02 --> about-us

The correct path is "about-us". But due to admins changing things I have ended up in a situation where there are sometimes old redirects lingering in the system. The problem is that these google says it's not good to redirect multiple times. So the above redirect is not very effective.

Is there a way that I can get Drupal 7 to automatically skip the 'middle' redirect if it knows that is only going to result in another redirect? So instead of:

about-us01 --> about-us02 --> about-us

I want:

about-us01 --> about-us
about-us02 --> about-us

In both cases of accessing the links, it must take you directly to the about-us page and not any inbetween links if it knows the true destination?


texts:
I don't want to add some commands I don't want to know where drush configuration file is I am simply looking for a file which contains drush command functions.

I am running drush on Ubuntu.


texts:
I have a date picker in my form, when user hits submit button, the date which entered in date field is displaying in list view. But I want to display the date the form submitted also.

Any help appreciated.


texts: Replacing Views Query and Displaying Results

texts:
I'm relatively new to Drupal and I am working on a view that needs to show both Users and Nodes in the same table. The solution that I have come up with is to use hook_views_pre_execute to replace the view query. However, after I've replaced the query, I just get a table with all blank values. It seems that the fields that I have added have no place to put there data.

This is my very basic test hook_views_pre_execute that I am using to try things out. I will be replacing it with something much more complicated once I get things working:

function hook_views_pre_execute(&$view)
{
  if($view->name == 'my_view_name')
  {
        // Basic setup of the second query.
        $query = db_select('users');
        $query->addField('users','name');
        $view->build_info['query']=$query;
  }
}

My view is set up with one field Content: Title which ends up being empty in the table. So how do I add the name column to my table view?


texts: How to print a flag in a block programmatically?

texts:
I am creating a module which displays a block. I have created a flag within the module, and I am trying to display it through the block_view() hook. Currently struggling to get there...

I am doing this instead of going through the template pages because there are certain conditions and functions involved to decide if I show the flag or not, making it easier for me at the minute to do this in a block.

Unfortunately, the block isn't working. Am I not displaying it correctly?

function get_involved_block_info() {
$blocks = array();
$blocks['get_involved_block'] = array(
'info' => t('Get involved block'),
'weight' => 10,
);
return $blocks;
}

function get_involved_flag_default_flags() {
$flags = array();
$flags[] = array(
'content_type' => 'node',
'name' => 'get_involved_interested',
'title' => 'Interested',
'global' => FALSE,
'types' => array('ad'),
'flag_short' => 'Join',
'flag_long' => 'I want to join',
'flag_message' => 'Your interest was registered',
'unflag_short' => 'Cancel',
'unflag_long' => 'Cancel my interest',
'unflag_message' => 'Your interest was deleted',
'show_on_page' => TRUE,
'show_on_teaser' => FALSE,
'show_on_form' => TRUE,
'status' => TRUE,
'locked' => array('name', 'types', 'global'),
);
return $flags;
}

function get_involved_block_view($delta) {
global $user;
$block = array();
if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);
$node = node_load($nodeid);

//First of all, if the user is the author, do not show this node
if ($node->uid == $user->uid)
{
} else {

$block['title'] ='Get involved';

$block['content'] = flag_create_link('get_involved_interested', $nodeid);

  return $block;
}
}


texts: Save image from URL to a field from a custom module

texts:
With a custom module, I'm trying to create a new node, save an image to a node's image field from URL and save the node as well. However when I'm trying to save the node, this error messages comes up

  Notice: Trying to get property of non-object in file_field_presave()
  (line 220 of
  /var/www/clients/client1/web20/web/modules/file/file.field.inc).

  Notice: Undefined property: stdClass::$uri in file_save() (line 566 of
  /var/www/clients/client1/web20/web/includes/file.inc).

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '' for key 'uri': INSERT INTO {file_managed} (filesize, status,
  timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0
  [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] =>
  1373886933 ) in drupal_write_record() (line 7136 of
  /var/www/clients/client1/web20/web/includes/common.inc).

This is the code I wrote for saving the image into a folder, saving it into a node field and save the node:

      $node = new stdClass();
      $node->type = "flickr_image";
      node_object_prepare($node);

      $node->title    = $photo['title'];
      $node->language = LANGUAGE_NONE;

      $node->uid = 1;

      $url = $image[10]['source']; //URL of the image
      $directory = file_build_uri('flickr_images/');

      $file = system_retrieve_file($url, $directory, TRUE, $replace = FILE_EXISTS_REPLACE);
      file_save($file);

      $node->field_image[LANGUAGE_NONE] = $file;

      if($node = node_submit($node)) {
          node_save($node);
      }

What am I doing wrong? I've looked up several similar questions here, but I don't understand what's the problem. The messages only come up when I use node_save(). When I comment it out, the messages disappear.


texts:
I have a few custom modules that updates are being served from a D6 site with the Feature Server (fserver) module. Before updating drush, the drush up command on a site would see there were updates for them just fine. Now I get:
$ drush up uni_blocks_antares
Update information last refreshed: Mon, 03/07/2016 - 09:13
Name                Installed Version  Proposed version  Message
uni_blocks_antares  Unknown            Unknown           Specified project not
                                                         found

No code updates available.                                           [ok]

But when I check that module's info it exists.
$ drush pmi uni_blocks_antares
Extension        :  uni_blocks_antares
Project          :  uni_blocks_antares
Type             :  module
Title            :  UNI Blocks Antares
Description      :  This module pulls in the feed of Toolbar and Footer links
                    from the UNI Features website and creates blocks
                    containing those links.
Version          :  7.x-2.7
Package          :  UNI Custom Modules
Core             :  7.x
PHP              :  5.2.4
Status           :  enabled
Path             :  sites/all/modules/custom/uni_blocks_antares
Schema version   :  module has no schema
Files            :  none
Requires         :  none
Required by      :  none
Permissions      :  none
Configure        :  admin/config/content/uni-blocks

I found that updating through the web interface of the site will see an update(version 2.8) and update the module.
How do I get drush up to work again for it?


texts: Redirect users from authentication URLs to signup page

texts:
I'm using Drupal 6.

I want to redirect users from /user/login, /user/register, /user to /sign-up if the user is the anonymous user. This page would show both login and register forms together.

The only page left would be /user/password, which form I don't want to have on /sign-up.
I'm comfortable with PHP, but I'm not sure about which hooks should I use to achieve this.

PS. I already know how to print those forms on my own. My doubt is just about the URLs.


texts: Guzzle POST HTTPS requests return 403 Forbidden only when called inside PHPUnit tests

texts:
On one side I have a remote Drupal 8 (8.8.1) served via HTTPS which has the following endpoint:

MODULENAME.get_notify:
  path: 'MODULENAME/get-notify'
  defaults:
    _controller: '\Drupal\MODULENAME\Controller\MODULENAMEApiController::get_notify'
    _title: 'Get notification'
  methods:  [POST]
  requirements:
    _access: 'TRUE'

On the client side I have a Drupal 8 (8.8.2) served via HTTPS which sends a notification using Guzzle library. This Drupal is local to my machine and is served via DDEV. Here is the Guzzle petition which is located in a custom module:

$options = [
  'headers' => ['Content-Type' => 'application/json'],
  'json' => $jsonArray,
  'timeout' => 15,
];
$response = $this->httpClient->post($url, $options);

The system works well except that when running PHPUnit tests (BrowserTestBase) of the involved module the POST query always return the following error:

Client error: `POST https://SERVER_DOMAIN/MODULENAME/get-notify` resulted in a `403 Forbidden` response'

Any idea why I get this error message?


texts: Customize Search Terms search criteria of the view

texts:
I am having a weird problem. I have made a exposed Filter "Search" field which allows a user to Search the results. It's a Search Term.

The problem is that it is not searching the results effectively.

Example: If I have a title XYZ-0123 and I search for XYZ, it would not give this result.

Any idea how I can customize the Search Term?

I'd greatly appreciate if you can assist here.

Here is a screenshot of the pop up in view. You can see there's no indication.


texts: How to add product thumbnails to Checkout?

texts:
I am wondering if anyone can help me figure this out. Using Drupal 7, and Ubercart 3x.

I'm trying to add the product thumbnails to the checkout pane as they show up in the "View Cart" pane. The table seems largely the same minus the fact that on the checkout page itself, there are no thumbnails of the products. I'm okay with PHP and poking around haven't been able to find how I could add this. Thanks!


texts: Can I change the default URI scheme in media.variables.inc?

texts:
The default URI scheme is public://, and I want to change it.

So, can I override the following code contained in media.variables.inc?

define('MEDIA_RESOURCE_URI_DEFAULT', 'public://');
define('MEDIA_TYPES_DEFAULT', '*');

What should I change at MEDIA_RESOURCE_URI_DEFAULT and MEDIA_TYPES_DEFAULT?


texts: how to print sql query of view in runtime

texts:
I would like to see view's sql query that is executed in runtime. I found this method in google, hook_views_pre_execute, but I am really beginner in drupal. Where I have to apply this method, when I put this method as project_views_pre_execute in template.php, nothing is shown and I don't know why, is it needed to write it in custom module?

Any suggestion is greatly appreciated.


texts: Views Accordion not working when other Jquery plugins are used

texts:
I am having problem with Views Accordion when I am using Views Accordion and the Isotope Jquery plugin both on same page.

Isotope Jquery plugin seems to be working fine, but the Views Accordion looks crashed no CSS and functionality is working.


texts:
I had installed module Commerce and it was giving me error whenever I try to display product.Then I went through forums to find out solution. And reason mentioned in forum was commerce module might not installed properly due to maximum execution time.So I decide to uninstall commerce module and  I have done. Also removed it from the sites\all\modules. I have cleared all the caches.

But question is that after removing the module, product(which is part of the commerce module) is still showing up in admin navigation bar at top.

I know it is not coding related question but still any help would be appreciated.


texts: DRUPAL_ROOT undefined on module installation

texts:
I try to install the live_agent module. When I go to enable the module, I get the following errors:

  Notice: Use of undefined constant DRUPAL_ROOT - assumed 'DRUPAL_ROOT' in /sites/all/modules/live_agent/live_agent.module on line 319

  Warning: require_once(DRUPAL_ROOT/includes/errors.inc) [function.require-once]: failed to open stream: No such file or directory in /sites/all/modules/live_agent/live_agent.module on line 319

  Fatal error: require_once() [function.require]: Failed opening required 'DRUPAL_ROOT/includes/errors.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /sites/all/modules/live_agent/live_agent.module on line 319

The code causing the error is the following one.

 /* 318 */ function live_agent_buttons_form(&$form_state) {
 /* 319 */   global $base_url;
 /* 320 */
 /* 321 */   $settings = new liveagent_Settings();
 /* 322 */   $la_buttons_grid = $settings->getButtonsGridRecordset();
 /* 323 */   $recordset = $la_buttons_grid->toArray();
 /* 324 */
             // ...
 /* 373 */ }

Any help on debugging this would be greatly appreciated.


texts: How do I theme a blog listing page for a specific taxonomy term?

texts:
I have a site, where a blog listing of a particular category, say Resources, has to have the "Read More" button say "Download Resource" instead.

I saw that this is controlled by a template file called 'node--blog-tpl.php' in the theme, with the following code:

    <?php if($extended == '1'): ?>
        <a class="btn readmore" href="<?php print $node_url; ?>"><?php print t('Read More');?>
    <?php endif; ?>

Since I wanted to change this just for the 'Resources' category, which was Taxonomy Term 23 for me, I copied this file and renamed it all manner of combinations/permutations of filenames with 'taxonomy--term-23' in it, but nothing seems to work.

Can someone please help me with this? I would be very grateful.

Thanks in advance,
Jasper


texts: How do I modify a webform submission field right before it is saved?

texts:
When an end-user is submitting data entered in a Drupal 8 webform, I would like my custom module to modify a field that is on the same form based on values of other fields. I am having trouble accessing the values of the submitted data and also setting the value of the field that I wish to change before being saved.

There is a sample webform API file included which has some starters for hooks. A hook which I found may be useful is the following.

function hook_webform_submission_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {}

I used the dpm() to print the values of these variables. The $form_state variable has the data submitted, and I know I can use the $form variable to change these values before being saved.

How can I get values of the data submitted and also set the value of another field on that same page before the submission is saved? In Drupal 7 this was fairly straightforward, but with Drupal 8 navigating the array and object structures of variables is not as transparent.