texts:
I have created a block through custom module. The content of the block should be random every time it loads the block. Call back function for this was written. The block also has a link say "Next" and when clicked on should reload the block with next random content.

How to get the block to reload without reloading the whole page when the link Next is clicked on?

Below is the module code I am using and js file.

/*
 * Implement hook_menu
 */

function my_module_menu(){
    $items['tips/reload']=array(
        'title' => 'Block Reload',
        'page callback'=>'reload_tip',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

/*
 * Implement hook_block_info().
 */
 function my_module_block_info(){
    $blocks['my_module']=array(
        'info' => t('My Tips'),
        'status' => TRUE,
        'region' => 'content',
        'weight' => 0,
        'visibility' => 0,
    );
    return $blocks;
 }

 /*
  * Implement hook_block_view().
  */
 function my_module_block_view($delta=''){
    switch($delta){
        case 'my_module':
            $block['subject'] = t('Teamie Tips');
            $block['content'] = my_module_block_content($delta);
            return $block;
        }

 }

 /*
  * tips block content function
  */
 function my_module_block_content($delta){
    $output = "
".getrandomtip()."
";
    $output .="Next";
    return array('#markup'=>$output);
 }

  function reload_tip(){
    $tip = getrandomtip();

    return drupal_json_output(array('nexttip'=>$tip));
    exit;
 }

 function my_module_theme(){
    return array(
        'my_module_javascript'=>array('arguments'=>array(),),
    );
 }

 function my_module_init(){
    theme('my_module_javascript');
 }

 function theme_my_module_javascript(){
    $jsfile = drupal_get_path('module','my_module').'/my_module.js';
    drupal_add_js($jsfile);
 }

and my js file is as below

 (function ($) {Drupal.behaviors.my_module = function (context){
    $('a#NextTipLink').click(function(){
        var nextTip = function(data){
            $("#divTip").html(data.nexttip);
        }
        $.ajax({
            type:'POST',
            url:this.href,
            success:nextTip,
            data: 'js=1',
        });
        return false;
    });

}})(jQuery);

When I click on next link, pop up is coming with file having json object. But I need to reload the blok content. Am I doing something wrong?


texts: #validate not overriding the submit function

texts:
I'm creating a form in my own module (call it mymodule) and using a #validate property to clear the form. In my form definition, after calling hook_menu and hook_form,

function mymodule_myform($form_state){
$form['main']=array(
    '#type'=>'fieldset',
    '#title'=>t('Information'),
    '#collapsible'=>TRUE,
    '#collapsed'=>FALSE,
);
$form['main']['title']=array(
    '#description'=>t('Enter title.'),
    '#type'=>'textfield',
    '#size'=>50,
    '#default_value'=>'default',
);
$form['submit']=array(
        '#type'=>'submit',
        '#value'=>'Submit',
);
    $form['clear']=array(
        '#type'=>'submit',
        '#value'=>'Reset form',
        '#validate'=>array('mymodule_myform_clear') //redirects to the _clear function defined below
);
    return $form;
}
    function mymodule_myform_clear($form, $form_state) {
        unset($form_state['values']);
        $form_state['rebuild']=TRUE; //clears the form
    }

    function mymodule_myform_submit($form, &$form_state) {
        $values=$form_state['values'];
        die('the value you submitted: '.$values['title']);

Both functions get called when the Reset from button is pressed. Why is the #validate property not doing its job?


texts: How to make a block visible only to one page

texts:
I have made a custom block and i want to make it visible only to pages that follow this pattern: user/[user-id]/galleries.

Is there a way to do it?


texts: Biblio module not seeing Bibtex or Google Scholar Lookup option

texts:
I am using biblio version 7.x-1.0-rc7 on a drupal 7.38 version site.

I am trying to do two things from the /node/add/biblio page:

Use the Google Scholar lookup to be able to get the info through the author name or book title but I don't see that option in the add content page.
I see online there are videos tutorials of people adding in existing bibliography data into a BibTex textfield - again I am not seeing that option when navigating to /node/add/biblio.

For some reason the only options I see is either the PubMed ID Lookup or the DOI Lookup. The publication type option just brings me to a blank biblio content where I would need to add all the date into fields not giving me an option to like just add the reference data in one text field.

This is what I see on the node add page:

This is the settings I have set on the biblio configurations page:

Any direction on how to get those options on the node add page would be greatly appreciated!


texts: How to export the log messages in .csv file?

texts: How can I export the log messages (Site Reports-->Recent Log Messages) in a .csv file?


texts: Migrate to node content type with the right user id (migrate module)

texts:
I want to migrate an old website (not Drupal) into Drupal.
I want to migrate a table to a specific content type...

Inside that table there are many fields in addition to the user_id field,
so every record has 'field_1', 'field_2', ..., 'field_n' and 'user_id' field (foreign key of table "users")

First I successfully migrated "users" table. The problem is that 'user_id' ( of old website) is not the same as 'uid' of the Drupal website.
For example assuming that the first record will be migrated, has the 'user_id' = 255. This user is already inserted with the 'uid' = 55 inside Drupal. Now I want to insert the node with the correct uid (witch is 55), but inside the table I have 255.

How can I do the correct mapping inside the Migrate class to insert every record inside "node" table with the correct 'uid' ?
Or if there is another solution to do it "All in one" (create users and the nodes at the same time) maybe Migrate module has some powerfull functionality like creating a temporary database table that tell the migrate classes that the uid 55 is the same as the user_id 255 of the old website...

Thanks in advance.


texts:
The structure of my form is as follows:

Form is built here

  function mymodule_member_search_form

The form submission processing happens in the callback function

  _mymodule_search_form_submit(&$form, &$form_state)

Here I am able to get the results and do the various processing I want and the final result I have stored in

if(isset($myvalues)){
        $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $myvalues,
        );
    }

But the values are not printed on the page after form submission, I have also set

$form_state['rebuild'] = TRUE;

in the above submission function

What am I missing here?

Additional Information is this form I have added as a block. So do I have to pass this ass the result of block? If yes, how do I do that?

Thanks.


texts: Using a .tpl to override a Views field that is being inserted in custom text field via token

texts:
My view contains 6 fields from a content type, and then one 'Global: Custom Text' field which I use to structure the view how I'd like.  Note that I remove all styling and containing elements on the hidden view fields.

The field, field_video_link is not using the tpl.php file I created for it only when it is used with the 'Global: Custom Text' field.  If I uncheck "Exclude from display", it renders using the custom template.

The HTML, along with tokens, that is contained in the 'Global: Custom Text' field is:

    [field_first_name] [field_last_name]
    [field_title]
    [title]

[body]

    [field_video_link]

The following is in views-view-field--field-video-link.tpl.php ('Here' is only printed to help me confirm):

<?php
  $output = 'Here';
  print $output;

When I view it, I only get the raw output from my field.  If I un-check "Exclude From Display" on the field in question, I get what you see in the screenshot included below.  Rendered by itself, it is just fine; within the "Global: Custom Text" it is not.


texts: How to display a node in overlay popup effect?

texts:
I have a content type 'students' with fields name, description and a photo. I have created a view(Block) to display only the images of the students. When the teacher/user clicks the photo of the student, It must show up the name, description and the photo of the student in a overlay/lightbox effect.

I have tried using Lightbox2 and colorbox node module to achieve as per my needs, But needed up in failure. Any help is widely appreciated.

Thanks.


texts: How does an entity get printed into a page after going though the page callback function?

texts:
This following code snippet is the value of page callback from hook_menu(). However, I cannot connect entity_view and the page template. How can I print or access the entity_view returned in this code from  my page template?

function example_task_view($task) {
  drupal_set_title(entity_label('example_task', $task));
  return entity_view('example_task', array(entity_id('example_task', $task) => $task), 'full');
}


texts: Print Primary and Secondary Menu Links separately

texts: I have a main menu with primary, secondary and tertiary links. The primary links will be positioned top right of the page. I want the sub menus (secondary/tertiary links) to print in a separate wrapper that will span the width of the browser. I cannot use absolute position because I need the sub menu to push down the content below it when I hover over the primary links. How can I do this with templates?


texts: How to theme "group by" header in a view

texts:
I'm using views to create a list of nodes grouped by a field.
The problem is that, in the html output, I've something like this:

Group title

content..

content..

Group title

content..

content..

I've put the group title and its contents in a common div, but which template do I have to work on?


texts: How to pass a variable $ _ GET in a page?

texts:
I will wish to create a privileged space for some users.

I create a role 'Candidate'. I assigned permission 'access user profiles' has this role.
I create a user that uses this role. (eg, foo)

Secondly, I create a menu (see below)

$items['candidate/%candidate'] = array(
  'title'            => t('My candidate space'),
  'description'      => '',
  'page callback'    => 'cel_configuration_custom_page',
  'page arguments'   => array(1),
  'access arguments' => array('access user profiles'),
  'access callback' => TRUE,
);

Then a linked function

function cel_configuration_custom_page($args){
  return 'custom';
}

Finally, I have emptied the cache.

When I go on the candidate/1 page with my account 'toto' or account 'admin', I have not found page.

Why?


texts: Is it possible to detect access to table on site db table and redirect the db query to a db shared by multiple websites?

texts:
I'm working on a project where I use a database that is common to all sites and another that is specific to each. Is there a way to detect access to a specific table on a contrib module (maybe using a hook) and redirect the queries to a table on the db of the shared site?

The contrib module in question is Oauth2.0 server and the table in question is the one where clients are stored, namely oauth2_server_client .


texts: What can we do to remedy the unrecoverable error we encounter for any Drush command?

texts:
We used Drush on our server without any problems up until now. Actually we didn't do / change anything relating to Drush.

But now, on every Drush command we issue, we only get an error like so:

  Drush command terminated abnormally due to an unrecoverable error.

Same error also occurs for Drush status. Only drush --version shows "Drush version: 6.6.0".

We installed drush via Composer. And the server is already restarted.

What can we do about this problem, which is a huge problem for us?


texts: Problems with extreme slow database queries in Drupal 7

texts:
I have a problem with extreme slow database queries that make my site loading for more than a minute. I am not able to locate the source of that problem. I'm using devel to control the queries and I found out that mostly the functions saving or updating the cache or session tables are the cause. Here is one example of devel's output:

19622.34 1 _drupal_session_write P A UPDATE users SET access=:db_update_placeholder_0 WHERE (uid = :db_condition_placeholder_0)
10442.86 2 DrupalDatabaseCache::clear P A DELETE FROM cache_bootstrap WHERE (cid = :db_condition_placeholder_0)

I do not have an idea what I could do to find the cause of that problem.


texts: How can i create two register forms for different users?

texts:
How can i have two register forms and show register form for two sets of users.

One register form for one set of users and another register form for another set of users?

one can be default drupal form that is user/register. But i want url to be varied.


texts:
I have a query with a 'BETWEEN' operator and I should have some results. Is there any way to show the actual SQL query made ?

Here is my entity query :

    $query = $this->entity_query->get('node');
    $query->condition('type', 'store');
    $query->condition('status', 1);
    if ($lat_min && $lng_min && is_numeric($lat_min) && is_numeric($lng_min) && $lat_max && $lng_max && is_numeric($lat_max) && is_numeric($lng_max)) {
      $query->condition('field_store_geolocation.lat', [$lat_min, $lat_max], 'BETWEEN');
      $query->condition('field_store_geolocation.lng', [$lng_min, $lng_max], 'BETWEEN');
    }
    $nids = $query->execute();

Of course I made sure that my values were the one expected and I also tried with '<', '>' and with no vars but actual values to make sure nothing was wrong there.

I'm using the 'Geolocation Field' module here.


texts:
I'm translating the site with my custom theme to another language. The problem is in menu links. On the original language they are fine, but with another one they are looks like "node/id". I've tried drupal_lookup_path with and without language, drupal_get_normal_path, drupal_get_path_alias but links are still the same.

I'm feeling like i've missed something in preference, but have no idea how to make links looks properly.

some code from my draw_menu function:

$items = get_menu_weight($menuName, $language->language);
foreach($items as $item) {
   $alias = drupal_lookup_path('alias',$item->link_path,$item->language);

...

    if ($item->link_path == "http://"){
    $drawItems .= '
'.$item->link_title.'';
   }else{
    if($alias == "/"){
        $drawItems .= '
link_title.'">'.$item->link_title.'';
    }else{
        $drawItems .= '
link_title.'">'.$item->link_title.'';
    }
   }

...

}

Thank you for your advises.


texts: Meta-Tag Module that can use existing fields

texts:
On my node, I have several existing fields, such as field_introduction and field_book_tags. These fields were created by me and do not come with Drupal by default.

I would like to know if there are any modules, which will let me use these fields for the Meta Description and Key word Tags.

The fields I need use for the meta tags will vary between content type, so the Meta tags solution must allow local overrides.

Here are some of the modules I have looked at:

Meta Tag, Custom Meta - Allows use of default Drupal fields only

Meta Tag Quick - Allows default Drupal fields only. Doesn't give much flexibility for selecting fields.

Simple Meta - Doesn't support any existing fields.

Beanstag - This allows the use of existing fields (via tokens). But, in order to target content types, a "folder" name has to be used in the URL (e.g. mysite.com/news/my-news for "news" content types, mysite.com/info/my-story for page content types). Although the folder name can be anything, I prefer my urls to be "folder" free (e.g. mysite.com/my-news)

It looks like BeansTag will have to make-do, but I thought I would ask in case anyone has better suggestions.


texts:
I have encountered a problem in my site. When the author of the node is anonymous, his/her content doesn't appear on the front page for anonymous users. but it does when the author is the admin.

Has anyone ever met the same issue and/or has a solution?


texts:
I am trying to make dynamic pages using hook menu which is going fine but the problem is I want to add page arguments for the states. For example if someone goes to the url and there isnt a state in the url like california for example(site/listings/california) it would show a page not found error, and if found it would list the listings I have looped out in my function.

Any Suggestions?

/*
** Hook Menu
*/

function listings_menu() {
    $items = array();

    $items['site/listings/%'] = array(
        'title' => 'City Listings',
        'page callback' => 'business_listings',
        'access arguments' => array('access content'),
        'page arguments' => array('states', 'city_names'),
    );

    return $items;
}

/*
** State Listings
*/

function listing_states($state){
    $state = array(
        'alabama' => t('Alabama'),
        'alaska' => t('Alaska'),
        'arizona' => t('Arizona'),
    //ect.....

    );
    return $state;
}

/*
** Company Listings
*/

function business_listings(){

    $states = listing_states(arg(2));

    $dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");

    $cityname = '';
    $cityname .= '
';
    foreach ($dbquery as $dbrow) {
        $cityname .='
';
        $cityname .= 'CityName)).'">'.$dbrow->CityName.'';
        $cityname .= '
';
    }
    $cityname .= '
';

    return array('states' => $states, 'city_names' => $cityname);
}


texts: Drush only partially working in both VM (Ubuntu) and host OS (Mac OS X 10.10)

texts:
I am currently running on a MacBook Pro with OS X 10.10 (Yosemite). That is the host machine and OS. I am using a synced folder between the host and my VM, which is running Laravel's Homestead VM (Ubuntu instance).

The project is a Drupal 7 project and I am running the latest version of Drush installed both on Mac OS X (via homebrew) and within the VM (I can't remember how I ended up installing it there). Very new setup, had the machine for a week and a half. Setup this way for maybe a week.

I am able to access and load the site just fine from the VM in my browser. It works great there. But, when I go to use drush against it (both in the VM and in Mac OS) it doesn't seem to give me most of the options.

Within the VM (ssh'ed in) I run "drush pml". Below is the message I get.

Command pm-list needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.                     [error]
The drush command 'pml' could not be executed.

I get the same message in Mac OS X. I am running the command from the docroot folder where drupal is installed. Not sure why this is. I could see it happening in the host OS. But it SHOULD be working within the VM that is running it and has the DB installed.

I haven't used Drush or Drupal for 2 years. So I probably forgot an obvious config or something. Please help me out here.

Thanks!


texts: Close a webform when total seats reach a maximum

texts:
I would like to know if it is possible to set-up a specific event registration webform to close automatically when the number of total reserved seats (reserved seats field) reaches a certain maximum.

A little background:
I have a few different event registration forms on my website, each event is held in a different venue with a maximum number of seats. The forms each have a reserved seats field, users can reserve up-to 2 seats(max) per submission. I cannot use the submission limit feature of the webform because the number of submissions do not map directly to the number of total seats that users are reserving.

Is it possible to have the webform calculate the sum of the reserved seats field and close the form when it reaches a certain maximum number? How would I go about setting that up?


texts:
I am using drupal 7. In theming i have created page--front.tpl.php

Every thing is working properly, but when i create a basic page and assign it to display on front page then page is not rendered.

I have also written this <?php print render($page['content']) ?> but content is not being rendered. It is showing error

  No front page content has been created yet. Add new content


texts: Is there any clean way to have the Drupal login form create a session for phpBB also?

texts:
I've made my peace with having two DB's and two sets of roles, permissions, etc. But I'd like to have just one login.

Is there a simple way to have the Drupal login throw a session cookie for phpBB with the same parameters as the drupal one?


texts:
I have two content types: Person and Office with existing content. The Person content type has an entity reference field to Office nodes, which only allows a single reference. I need to change this to allow an unlimited number of Office nodes to be selected.

Drupal 8 prevents changing the cardinality of the field, and it gives the following error message.

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

At first, I thought I needed to write a migration, but they seem to be aimed at bringing data into a Drupal instance. Then, I read about writing update functions (also this documentation).

I discovered a migrate-plus plugin that adds a couple pages me to export the field storage settings, change the cardinality, and re-import the settings.
Given that I'm going from cardinality of 1 to unlimited, I could imagine this change wouldn't destroy data. And my empirical data suggests this is the case. I've now made this change via the migrate-plus screens as well as via configuration export and import and the data is still in the field.

Is this a safe operation, or should I write an update function?


texts:
I have a Drupal 7 site, where I created a new page which became my front page.

Drupal requires that the page have a title and I've found no way of removing the title from showing on the page. At the moment, I have the title as "Welcome".
I'd like to remove it completely from the page or make it invisible.
I'm looking for the easiest method to accomplish this.


texts: How to add a views block in a basic page via editor?

texts:
I have created a basic page through the editor of drupal 7 and I have started coding the body using the PHP code text format. So far so good, apart from the fact that I want to embed a block from a view (showing three nodes) and the code below which seems to work when I put it directly into a php file, doesn't activate within the body. I am using Bootstrap by the way.

    <?php print views_embed_view("mylatest_events", "block"); ?>

Flavour text to describe the view here.

Any suggestions?


texts: How to send email in every 7 days to in-active users that is not logged in since 7 days?

texts:
I want to send mail in every 7 days i.e please login site, you are not logged in since 7 days, only for those users which are not logged in since 7 days. I have already created an event i.e After creating new user a/c. But I don't think so that this event is good for existing users.

What event I need to add? What condition am I apply to check [account:last-login]<7 days & send mail in every 7 days.

Please Help. Thanks


texts: Change remove from cart button to an image button

texts:
I want to change the remove-button, that removes line items from the cart to an image button representing a trash can like this:

The code I am using in a custom module looks like this:

<? php
function mymodule_custom_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  foreach ($form['edit_delete'] as &$item) {
    $item['#type']='image_button';
    $item['#src']='sites/all/themes/mytheme/images/trash.svg';
    $item['#alt']='Remove';
  }
}

That code shows the icon instead of the text as expected, but unfortunately it introduces a major issue: now pressing the button doesn't remove the correponding line item, but wrongly successively removes the last added line-items. So when I added item1, item2, item3 to the cart in this order, then no matter which corresponding remove-button you press, item3 is removed. Next time, you press one of the remove-buttons of the remaining 2 line-items, then item-2 is removed.
What's wrong with the above code?


texts:
Is or are there currently a module(s) that redirects users of a drupal site to enforce a SSL connection on parts of the website?

Essentially accomplish the following use case:

  A user visits a glob pattern: /cart/*, / it enforces https://
  connection as well as redirects any images/javascript to utilize a ssl
  connection.


texts: Defining module.links.action.yml with route parameters

texts:
How can I pass dynamically route parameters to module.links.action.yml?

My code of module.links.action.yml:

module.group_apply:
  route_name: module.group_apply
  title: 'Subscribe to group'
  weight: 0
  appears_on:
    - entity.node.canonical

My code of module.routing.yml:

module.group_apply:
  path: '/projects/{project}/usergroup/{group}/subscribe'
  defaults:
    _controller: '\Drupal\module\Controller\SubscriptionController::subscribe'
    _title: 'Apply'
  options:
    parameters:
      project:
        type: entity:node
      group:
        type: entity:node
  requirements:
    _permission: 'access content'

My subscibe function (actually):

public function subscribe(NodeInterface $project, NodeInterface $group) {
    return array(
        '#markup' => 'HERE WE GO!',
    );
}


texts: Database log messages (auto cleaning) with keeping exceptions

texts:
I can see that the Drupal has a settings about logs to keep, but when some amount is configured, so after X logs, the oldest are deleted.
Is there any option to make some logs not to be deleted?


texts: Why I not get value from $form_state['values']['field_form_name']

texts:
I created module_templat with code:

<?php

 function module_template_menu(){
    $items = array();
    $items['them-noi-dung'] = array(
        'title' => t('Khai báo hóa chất'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('module_template_select_form',2),
        'access callback' => true,
    );
    return $items;
    }

function module_template_select_form($form, &$form_state){
    $form = array();
    $form['select'] = array(
        '#type' => 'radios',
        '#title' =>'Lựa chọn hình thức khai báo',
        '#options' => array('0'=>t('Khai báo lần đầu'), '1'=>t('Đã từng khai báo')),
        '#default_value' => '0',
    );
    $form['ma_so_thue'] = array(
    '#type' => 'textfield',
    '#size' => '20',
    '#title' => 'Vui lòng nhập vào Mã Số Thuế',
    '#states' => array(
        'visible' => array(':radio[name="select"]' => array('value'=>'1'),
                    ),
            ),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Tiếp tục'),
    );
    return $form;
    }

function module_template_select_form_submit($form, &$form_state) {
    $select = $form_state['values']['select'];
    $masothue = $form_state['values']['ma_so_thue'];
    if(isset($select)){
        $masothue = $form_state['values']['ma_so_thue'];
        $form_state['redirect'] = 'node/add/khai-bao-hoa-chat';
        }
    }

function module_template_form_alter( &$form, &$form_state, $form_id ){
    $masothue = $form_state['values']['ma_so_thue'];
    if ($form_id == 'khai_bao_hoa_chat_node_form') {
        $form['field_ten_to_chuc']['und'][0]['value']['#default_value']= $masothue;
        }
    }
function module_template_theme($existing, $type, $theme, $path) {
    $items = array();
    $items['khai_bao_hoa_chat_node_form'] = array(
        'render element' => 'form',
        'template' => 'khai-bao-hoa-chat',
        'path' => drupal_get_path('module', 'module_template'),
        );
    return $items;
    }

Why I  can not get value of $form_state['value']['ma_so_thue'] in module_template_form_alter(&$form, &$form_state, $form_id) when form submited?


texts:
Is there any way to have rss feeds for individual nodes, taxonomies and so on.Right now we have rss feed for the entire website.

for example :
I'd like to access a node feed through http://www.musite.com/node/1.xml


texts: OG: Only allow certain Drupal roles to join a group

texts:
I think this might be a very simple setting I am missing somewhere, but I want to prevent people from joining an 'Organic Groups' group unless they have a particular Drupal role. The 'subscribe to group' permission in the group obviously only applies to OG roles, not Drupal's core roles.

I can't see any permission in Drupal's core for 'join group type', which I would have expected.

Any ideas?


texts:
I would like to know how I can include additional URL parameters to a given link? ie: 'news?pid=3'

<?php
print $path='news?pid=3';
?>

This returns page not found error as the '?' is getting printed as %3F.


texts: How to provide a specific node template in a custom module

texts:
I am using a custom module and using Bartik theme(from Drupal 8 core module) and hence need to define a content type specific template like node--[type].html.twig

I added hook_theme in my custom module as follows

function custom_autofill_reference_theme($existing, $type, $theme, $path){
   drupal_set_message($path);
   return [
    'node' => [
      'path' => $path . '/templates',
      'template' => 'node',
    ],
  ];
}

but not sure on how to add a content type specific template in a custom module without the need to create a custom theme?


texts:
How to set a view title from page title dynamically, as if the page node title is About the Company I want the corresponding view title to be the same as node title.

any suggestions


texts: Lightbox doesn't show images loaded by entity_metadata_wrapper

texts:
There is a field collection in a content type, it's name is field_jeld. This field collection has an image field, it is field_image. I also defined an image style called book_mini. I need to load the images using lightbox, to do so I set the following image format in manage display of every display mode:

I have to load the images in the front page so I used entity metadata wrapper, this is my code:

$nid = "A NID GET FROM SOMEWHERE ELSE";
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node',$node);
$jelds = $wrapper->field_jeld->value();
foreach ($jelds as $jeld){
    $item_id = $jeld->item_id;
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $item_id);
    $photo_field = $fc_wrapper->field_image->value();
    $image = theme('image_style',
        array(
            'style_name' => 'book_mini',
            'path' => $photo_field['uri'],
        )
    );
    print $image;
}

This code prints the image in book_mini format very well but the problem is, when I click on it, it is not loaded by lightbox and no popup is shown, in fact the image is not a link. How do I can solve this problem?

UPDATE1

I also tried this

$nid = "A NID GET FROM SOMEWHERE ELSE";
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node',$node);
$jelds = $wrapper->field_jeld->value();
foreach ($jelds as $jeld){
    $item_id = $jeld->item_id;
    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $item_id);
    $photo_field = $fc_wrapper->field_image->value();
    $image = theme('image_style',
        array(
            'style_name' => 'book_mini',
            'path' => $photo_field['uri'],
        )
    );
    $name = $photo_field['filename'];
    $url=  $base_url."/sites/default/files/image/".$name;
    print "".$image."";
}

I'm sure the $url points to the right file, after clicking the browser opens the lightbox but it doesn't show image, only white screen!

UPDATE2

The only solution I found is to use filed collection views and Views. I created a View called loadcover and selected field_jeld as a field. I also created a View of field collection views, called fc_jeld, and selected the required fields. This is the Formatter configuration of field_jeld :

Then using this code

print views_embed_view("loadcover","block",$nid);

it worked ! sounds the lighbox works with field collection only in the Views not the node!!!


texts:
Example I have webform at http://www.example.com/webform. Once I submit the form it will redirect to confirmation page which is http://www.example.com/node/8/done?sid=18&token=ggffdgdf7g8df7g89d7fg98df77

May I how to get this token value from database? I had tried md5() for submitted time, but the value is not the same.


texts: Access callback infinite loop in specific case

texts:
I need to limit node creation to one item for a specific content_type (photography contest), and to redirect the user to its photography if he already posted one. The snippet below is almost working as expected.

function mymodule_menu_alter(&$items) {
  $items['node/add/slide']['access callback'] = '_mymodule_limit_slide';
}

function _mymodule_limit_slide () {
  global $user;
  if(user_access("create slide content")) {
    $allowed_limit = variable_get('allowed_limit', 1);
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    if ($slides['ct'] < $allowed_limit || in_array('administrator', $user->roles)) {
      return TRUE;
    }
    else {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto(drupal_get_path_alias('node/'.$slides['nid']));
    }
  }
  return FALSE;
}

If I dpm(slides), it returns the correct array and data.

But, as far as I could debug, if I try to connect a user who :

already posted at least one node of other content type
whether he posted or not a slide

Drupal tries to go to node/'.$slides['nid'] and that creates an infinite loop.

Summary : I don't understand why my function _mymodule_limit_slide () would be called out of node/add/slide url, or what else is wrong ?


texts:
I'm using the Paragraphs and Block field modules to display a list of nodes within the content of a page. This works great while authoring, but as soon as I log out from the administrator account, the node list vanishes from the page. The component is still there, but the content is not rendered.

Here's is the twig template for my block paragraph type:

{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
'paragraph--id--' ~ paragraph.id.value,
]
%}

<div{{ attributes.addClass(classes) }}>
  {{ content }}
</div>

Not a lot going on, as you can see.

Does anyone have any experience with the block field module and can walk me through this?

EDIT:

I did some digging into the block field module source, and determined that this is the line of code causing the failure:

if (!$block_instance || !$block_instance->access(\Drupal::currentUser())) {

More specifically, it's the second condition. So for whatever reason, the current user doesn't have access to the block instance unless the current user is an administrator. Does anyone know how to solve this?

EDIT 2: I should probably mention that the blocks I'm trying to show are created by a view. I double checked that the access property on the generated blocks should allow all user roles.

EDIT 3: I did a little more digging, and verified that if I return AccessResult::allowed() from Drupal\views\Plugin\Block\ViewsBlockBase::blockAccess, the problem disappears. So what's happening is the view is saying the block ID is inaccessible for some reason.

EDIT 4: I discovered that setting the "Bypass content access control" permission on all users fixes the issue. However, I'm not sure this is desirable. Is there a way to fix the issue without setting this?


texts:
One of my tasks requires me to disable the links to username and date fields generated from diff_diffs_show() whose output is rendered as in the following screenshot.

The code outputting those links is the following one.
// Generate table header (date, username, log message).
$old_header = t('!date by !username', array(
  '!date' => l(format_date($old_node->revision_timestamp), "node/$node->nid/revisions/$old_node->vid/view", array('absolute' => 1)),
  '!username' => theme('username', array('account' => $node_revisions[$old_vid])),
));
$new_header = t('!date by !username', array(
  '!date' => l(format_date($new_node->revision_timestamp), "node/$node->nid/revisions/$new_node->vid/view", array('absolute' => 1)),
  '!username' => theme('username', array('account' => $node_revisions[$new_vid])),
));

How I can change the output of the function so that it doesn't output links?
Basically, I want the username  and date fields in plain texts instead of links.


texts:
I have following installations:

openjdk version "1.8.0_171"

Solr running on port 8983

"solr_home":"/var/solr/data",
"version":"6.5.1 cd1f23c63abe03ae650c75ec8ccb37762806cc75 - jimczi - 2017-04-21 12:23:42",

Server OS:

Red Hat Enterprise Linux Server release 7.4 (Maipo)

Though the Solr is running on the server I am unable to use it for my site (Drupal  7.38).

I have set Solr server URL as:

http://localhost:8983/solr

I am getting an error:

Your site was unable to contact the Apache Solr server.

What could be the issue? How can I solve it?


texts: How to remove the Day field from a Date?

texts:
I want to remove the day field from a Date dropdown of a webform. How to do that? I tried with hook_form_alter() without success. Any suggestions?
Thanks


texts:
Is there a way to disable a Rules Component? And if so, -how-?

Using Commerce, I've set up various Sales Taxes. If I understand, the Rule for Sales Tax triggers all 'Components' to be evaluated which are of type Sales Tax and then executes any/all that match the condition.

But in our case, we -know- ahead of time, that some of those Components will never be executed, so I was hoping for a way to prevent them from being evaluated and thus speed execution.

I'd prefer to keep some Components 'disabled' rather than delete them in case we need them in the future or for importing old orders.


texts: How to use user_external_login_register() with user authenticated by token?

texts:
So, I'm working on an Oauth2 implementation, and I'm forced to use a custom module as the existing modules all have slightly differing functionalities than my use case, assume Drupal-to-Drupal implementation, or request the user credentials to be submitted to the remote server (which is not how Oauth should be implemented).

Using the standard authflow, the users are redirected and authenticate against a remote server, and are returned with an access code which is then submitted for an auth token, which is finally used to get user info from the remote API. Finally, I take the json response, format it into an array to be created into an user object, and this is where I'm stuck.

The examples presented on the User External Login Register API page seem to assume querying an external database to check for the user's existence. In my case, I have the user info and name, and need to create a user and log them in with that information.
 This is my current attempt which doesn't seem to be working. I modified the API example use the user_load_by_name() function to see if the user exists. Otherwise, I'm not sure how I should approach this otherwise.

So, my question is: 1) How do I correctly use this function? the example uses it without a module prefix, but if I declare it as a regular function I get a fatal error about re-declaring functions.

  $cs_user = array(
        'name' => $user_info['data']['user']['lastname'] . "_psr",
        'mail' => $user_info['data']['user']['email'],
        'pass' => $user_info['data']['user']['lastname'] . "_user_pass",
        'init' => $user_info['data']['user']['lastname'] . "_psr",
        'signature_format' => 'full_html',
        'status' => 1,
        'roles' => array(DRUPAL_AUTHENTICATED_RID => 'authenticated user',
                            22 => 'CS User External',),
        'field_first_name' => array(array('value' => $user_info['data']['user']['firstname'])),
        'field_last_name' => array(array('value' => $user_info['data']['user']['lastname'])),
        'field_chapter' => array(array('value' => $user_info['data']['user']['groups']['0']['title'])),
       );
    //format the user info, feed it to external_user_login_register
    $name = $cs_user['name'];
    $module = 'chapterspot_signon';
    echo "<hr>";
    }
    function chapterspot_signon_user_external_login_register($name, $module){
        $account = user_load_by_name($name);
$account = $name;
        if (!$account) {
        // Register this new user.
        $account = user_save(drupal_anonymous_user(), $cs_user);
        // Terminate if an error occurred during user_save().
        if (!$account) {
          drupal_set_message(t("Error saving user account."), 'error');
          return;
        }
        user_set_authmaps($account, array(
          "authname_{$module}" => $name,
        ));
      }
      // Log user in.
      $form_state['uid'] = $account->uid;
      user_login_submit(array(), $form_state);
      drupal_goto('/members');
    }

Update: The issue here is how to instantiate the function? The API page shows the function being called without a module prefix. When I run the code as user_external_login_register() I get a fatal error. When I try to run the function as mymodule_user_external_login_register nothing happens e.g.

$name = $cs_user['name'];
$module = 'chapterspot_signon';
function chapterspot_signon_user_external_login_register($name, $module){
echo "This is working";
}

Update 2: Apparently, the code within the function works by itself.


texts: How can I select which tags should be stripped from the footer?

texts:
In Drupal 6, the footer message is stripped of some HTML tags. In my case I want to place <img> with a <map> tag so the image would link to different sections. Drupal strips off the <map> tag, even if I add it to the accepted HTML tags in "Filtered HTML" data type.

Is there a way to enable the <map> tag in the footer?


texts: How do I fix this Configuration Directory sync error?

texts:
I can't get past this error while installing drupal on my localhost.

I've chmod'ed permissions on my core /default directory. I've:

/default on 755
/default/files including all subfolders and files on 744 (or 755)
/default/themes including all subfolders and files on 755
/default/modules including all subfolders and files on 755
/default/settings.php and /default/default.settings.php on 444

I've even double checked my apache configs to prepare for drupal8 install.

I'm stumped. I'm out of room to config everything. What's the proper course of action to fix this problem?


texts:
I have installed FileField Sources module. I am using "Remote URL" option for file Upload. While adding content when I am giving the image url say "http://www.abc.com/test.png", the file is not getting transfered.Instead it is not showing up anything.

Any help would be appreciated.


texts: How can a controller change the url reported to browser?

texts:
I have got two routes - one is for pausing mail jobs, the other one for listing them.

When I click on "pause" - the pause route:

does it's thing
internally calls the list route with a couple of extra nontrivial parameters and fetches it's render array
returns render array

However, I'd like the browser to report the url of the list-route instead of the pause-route. How can I achieve this?


texts:
I'm using a view template to override how a field is displayed.

I want to include a link to the node in the field.

Given a node, how do I get the URL (relative is fine) for a node?

I've got the node in the overridden template, but not sure where to go from there:

$node = node_load($row->{$field->field_alias});
$wrapper = entity_metadata_wrapper('node', $node);

$path_to_node = ???

?><a href="<?php print $path_to_node ?>">Go to Node


texts: how to get nid of a node when user is not on a node page

texts:
I had made a custom form and want a field in it that would work as a node reference field. Currently iam not on the node page but i want the nid of nodes of a content type to be the options of the select field which is my node reference field. here is the code for the select field that should work as node reference field.

function formModule_form($form, &$form_state) {

    $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('What is your Qualification?'),
    '#required' => TRUE,
    '#options' => array(
      '1' => 'UnderGraduate',
      '2' => 'Graduate',
      '3' => 'Post Graduate',
         ),
    '#description' => t('Choose an option.'),
  );

return $form
}

the #option in the above code should have the nid of nodes.


texts:
I can't figure out how to add an IN clause in my query, using placeholders.

I'd want it to be something like:

$nids = array(1, 2, 3);
$result = db_query('SELECT * FROM {node} WHERE nid IN :nids', array(':nids' => $nids));

Can't find any documentation on this simple task. What's the proper way to achieve this?


texts: How to download Database results as PDF or in EXCEL

texts: I have a custom query to fetch the details from database (oracle). The results are generating properly as expected. Now i need to download these results either a PDF or an EXCEL file. Any way to achieve this


texts:
I need to make a form that autofills itself with some values that I give from the GET or POST params

I have an emailing that is personalized for each user so when they click on a link or a submit form they will view that webform autorefilled with their data

I'm using Drupal 6.19 and Webform 6.x-3.4


texts: How to format the raw date formats when using Google Analytic Reports?

texts:
I am using Google Chart Tools, Views, and Google Analytic Reports to create charts for an admin dashboard.

However the date format (Time Dimensions: ga:date) outputs the date in the YYYYMMDD format.

How can I change that to something like Oct 31?

Note: I have been asking around and apparently NO ONE knows how to do this. Here are some relevant URLs about it:

Date Format in Views, related to the Views Dataviz with Google Charts API module.
Google analytics with views and google chart tools, related to the Google Chart Tools module.
Format time duration (not the exact same issue, pretty close).


texts: Module Views slideshow unable to uninstall

texts:
I am going to upgrade my Drupal 6 to Drupal 7.

Before doing migration, I clear all optional module check boxes and remove unwanted modules in Home > Administrator > Site building > Modules > Uninstall (In Drupal 6)

The module below can't delete. While I press "uninstall", my site redirect to site.com/admin/build/modules/uninstall/confirm and it is blank page.

  Name: Views slideshow: DDblock Examples

  Description: Slideshow examples using image field. Installs content type, view and example content.

Would skipping this step effect the migration?


texts: How to add template suggestions for entities?

texts: I need to add a template suggestion for entities in a custom module, similar to how you can add one for nodes. I've seen the ones implemented in the Entity API module, but how do I hook into entity preprocessing so I can add my own?


texts: Drupal 8 Development - How to Loop Through Field Formatter Elements

texts:
All-- I'm trying to wrap my head around Drupal 8 development, and I'm trying to create a very simple field formatter.  It's being applied to a multi-file field, and I'm just trying to display information for each file uploaded to a custom content type that uses this field.

But-- I'm having issues figuring out exactly how to properly pass data from my PHP files to my Twig template. The code and Twig template below are displaying info about the two files uploaded to a page just fine, but as you can see, I'm not looping through an array of items; I'm just inserting the variable names for some metadata I'm trying to display for some file objects, yet it's looping through and displaying the info for each file uploaded to the page even though I'm not doing a Twig loop.  Also-- if I add HTML above or below the Twig template placeholders ({{uri}} and {{filename}}), the HTML is being duplicated for each file that has been uploaded to the page.

So long story short: how should I massage my code to pass data to Twig such that I can loop through it with a Twig loop (e.g., {% for item in items %}) and also prevent any additional markup in the Twig template from being duplicated?

NOTE: here is the original viewElements() function that I was using, and that was causing my issue; all the code after this block is the final code that actually works:

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = array();
    foreach ($items as $delta => $item) {
    // Render each element as markup.
      $element[$delta] = array(
      '#items' => array(
      'uri' => file_create_url($item->entity->get('uri')->value),
      'filename' => $item->entity->get('filename')->value,
      '#theme' => 'video_file_display',
    );
   }
   return $element;
 }

From FieldFormatter PHP file:

public function viewElements(FieldItemListInterface $items, $langcode) {
$element[0] = array(
  '#theme' => 'video_file_display',
);
foreach ($items as $delta => $item) {
 $element[0]['#items'][] = array(
    'uri' => file_create_url($item->entity->get('uri')->value),
    'filename' => $item->entity->get('filename')->value,
  );
}
return $element;
}

From .module file (hook_theme):

function field_formatter_test_theme(){
  return array(
    'video_file_display' => array(
      'variables' => array(
        'items' => array(
          'uri' => NULL, 'filename' => NULL),
        ),
      'template' => 'video-file-display',
    ),
  );
}

Twig template:

Here is my page

{% for item in items %}
  {{item.uri}}

  {{item.filename}}
{% endfor %}

{{ kint() }}

Sample page output:

Here is my page
Twig context array(15)

(and examining the kint output shows null values for 'uri' and 'filename')


texts: How to get the File Description on a custom field formatter?

texts:
Greetings to all of you.

This is my first question posted around here, so any suggestions are welcome on improving how to better formulate questions.

Into the matter.
I have the following code in a Drupal 8 site:

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\MyModuleFormatter.
 */

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Url;

/**
 * Plugin implementation of the 'mymodule' formatter.
 *
 * @FieldFormatter(
 *   id = "mymodule",
 *   label = @Translation("My Module"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */

class MyModuleFormatter extends MyModuleFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = array();
    $files = $this->getEntitiesToView($items, $langcode);

    /**
     * Early opt-out if the field is empty.
     */
    if (empty($files)) {
      return $elements;
    }

    foreach ($files as $delta => $file) {
      $file_uri = $file->getFileUri();

      $elements[$delta] = array(
        '#theme' => 'mymodule',
        '#files' => array(Url::fromUri(file_create_url($file_uri)));
      );
    }

    return $elements;
  }
}

So far so good. Everything is working.

Now, I would like to include in $elements the file description.
Something like:

foreach ($files as $delta => $file) {
  $file_uri = $file->getFileUri();
  $file_description = <someting> // That's what is needed...

  $elements[$delta] = array(
    '#theme' => 'mymodule',
    '#files' => array(Url::fromUri(file_create_url($file_uri)));
    '#descriptions' => array($file_description);  // ...so it can go here.
  );
}

As stated by Berdir, it looks that the description is stored on the file field, not on the file entity.
Yes, seems to be there, somewhere in $items.

How to get it?

Many thanks.


texts:
I'm trying to update my colorbox module and I keep getting the error:

  Update failed! See the log below for more information. Your site is
  still in maintenance mode.

and below it says:

colorbox

Error installing / updating
File Transfer failed, reason: Cannot remove directory /home/content/02/12910502/html/sites/all/modules/colorbox/..

Next steps
Your modules have been downloaded and updated.
Run database updates

why do I get this error and how can I get this fixed?

EDIT1
I'm using GoDaddy shared hosting. All permissions for files & directories in ftp are set to 755 (owner 12910502) within colorbox/ but I still get this error... - I've never had a problem on other sites I'm working with, weird.
This is drupal core 7.15 - may that be the reason?

EDIT2
How abut if I just replace the directory onthe ftp with the latest version and then run update.php, should this work too?


texts: how to inject dependencies into an access controller?

texts:
I am altering an existing route and adding a custom access. The custom access is a method that I want to have it in it's own access controller:

  /**
   * Alters existing routes.
   */
  public function alterRoutes(RouteBuildEvent $event) {
    $collection = $event->getRouteCollection();

    if ($route = $collection->get('entity.node.clone_form')) {
      // Add custom access
      $route->setRequirement('_custom_access', '\Drupal\eclone_extras\Controller\EcloneExtrasAccessController::access');
    }
  }

Then in my access controller I have:

namespace Drupal\eclone_extras\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class EcloneExtrasAccessController extends ControllerBase{

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The entity type ID.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * Constructs a new ContentEntityCloneBase.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param string $entity_type_id
   *   The entity type ID.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, $entity_type_id) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeId = $entity_type_id;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $container->get('entity_type.manager'),
      $entity_type->id()
    );
  }
  /**
   * Custom access checker for the create lock requirements route.
   *
   * @see \Drupal\content_lock\Routing\ContentLockRoutes::routes()
   */
  public function access() {
    // do access stuff
    return TRUE;
  }

}

But I keep getting the following errors:

0 passed in /var/www/drupal8/web/core/lib/Drupal/Core/Controller/ControllerBase.php on line 118 and exactly 2 expected in Drupal\eclone_extras\Controller\EcloneExtrasAccessController->__construct() (line 36 of modules/custom/eclone_extras/src/Controller/EcloneExtrasAccessController.php).


texts: Where is the the site name and slogan set?

texts:
In the page--front.tpl.php template, I have the following code for site logo.

<img src="<?php print $logo ?>" alt="example.com logo" title="<?php print $site_name_and_slogan ?>" id="logo" />

Where is the title set in Drupal 7? Right now the title is showing blank in the production site.


texts: How to edit the label color for published or not published in Admin?

texts:
I tried to change the color of the text under the "Published" column of the node content listing.

I need the published text to be in green color and the unpublished text to be in red color.

In the view I have edited the output of the following field:

Administration: Nodes (Content)

Configure field: Content: Published

Rewrite Output :

[status]

Please check the screen shot for a better understanding.


texts: How to calculate field values in Views Calc?

texts:
In Drupal 7, I have a custom content type containing distance (a decimal field) and time (a date field where only hours, minutes and seconds are entered).

In a view on that custom content type, I would like to show not only distance and time but also speed. (speed = distance / time)

I already tried to create a formula in views calc but:

I didn't find a way to get the hour, minute and second values separately from the date field. When I tried to define DATE_FORMAT (%field, '%i'), I got an error mentioning that i is not an allowed value.
I tried to work with the value of %field directly (because I found out that the field contains 101HHiiss as value) but I coulnd't define something like %field / 1000000 because then I would get an error mentioning that 00 is not an allowed value.


texts: Making title unique using hook_entity_bundle_field_info_alter()

texts:
hook_node_validate() is replaced by hook_entity_bundle_field_info_alter() in Drupal 8.

I need to validate the node title whether the same title is used in any other node. Title field should be unique for me.

How can I define that in hook_entity_bundle_field_info_alter()? When I print something in this hook. It didn't called when I save the node.

function my_module_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node') {
    dpm($entity_type);
  }
}

What am I doing wrong?


texts: Panel Content not displaying correctly after migrating site to new server

texts:
This is how it looks like after I migrated the site. I compared the new panelizer and panels folders with a backup folder that I had  to see if there were discrepancies, but the folders had the same files. I also resaved the admin page as suggested in another post, but that didn't do it for me.

I am using D7 by the way.


texts: Create a view with the contents of "self"

texts:
I am creating a View that will list all the current user's submissions of a specific content type. It is called "My Submissions".

However, I can't find a way to filter all results to "where author is me". Where could I achieve such thing?


texts: View conditional logic based on dropdown value

texts:
I have a view that is outputting fields from a paragraph. I want to be able to output different markup. There are two available values in the dropdown

1|Wrapping Link
2|Internal Link

and they should determine if the markup is wrapped by a link or if the same link is a contained within the markup as a stand-alone link.

In my custom version of views-view-fields.html.twig I want to have some logic in place that will check the value of the dropdown and display the correct markup. I have tried the following but this is invalid.

{%- if {{ fields.field_banner_type.content }} = "1" -%}
    // wrapping link
{%- else -%}
    // no wrapping link
{%- endif %}


texts:
I need to be able to easily get a list of available updates for a site.

I've come across the update_get_update_list() function, but that only returns an array of " information about database updates that need to be run, and any updates that are not going to proceed due to missing requirements." I want the list that gets displayed on the admin/modules/update page, but can't seem to find any way to do that through the core update module, and want to avoid using grep on a drush up -n call (as that feels kind of hacky.)


texts: How to set mysql port for Drupal and Drush

texts:
My site was running fine with the following default setting in settings.php file:

'host' => 'localhost',
'port' => ''

Then I created a separate mysql instance on another port:

'host' => 'localhost',
'port' => '123'

But this does not affect drupal - it still connects to the old db on default port!

With the following settings drupal connects to the new db, but now I can`t make archive-dumps with drush. Drush reports an "Unknown MYSQL server host error".

'host' => 'localhost:123',
'port' => ''


texts:
I am stuck since yesterday on a problem that is making me crazy, I feel like I am missing something.
Here is the context:
I am products (a node). In each products, I have tags (taxonomy terms), in a term reference field with an unlimited values possible.

I am simply trying to query my items, using a tag filter. But as soon as I select multiple tags, if the multiple as those tags, results is multiply by the number of corresponding tags.

The query is pretty big so I am simplifying it here to achieve the same result.

Node structure:

Title ------- | Quantity | Tags Tid
Product 1 --- | -- 1 --- | 12, 15
Product 2 --- | -- 4 --- | 13

Tables looks like this:

Node:

Title ------- | Nid
Product 1 --- | 320
Product 2 --- | 321

Quantity:

quantity_value | entity_id
1 ------------ | 320
4 ------------ | 321

Tags:

tid | entity_id
12  | 320
13  | 321
15  | 320

I am using db_query for my query:

So let's say that I want to filter on product that has Tags tids equal to 12 and 15 (product 1)

$query = db_query("
  SELECT n.title, SUM(q.quantity_value)
  FROM {node} n
  JOIN {quantity} q
  ON q.entity_id = n.nid
  LEFT JOIN {tags} t
  ON t.entity_id = n.nid
  WHERE t.tid IN (12, 15)
  GROUP BY n.title
  HAVING COUNT(DISTINCT t.tid) = count(12,15)
");
$results = $query->fetchAll();

That query returns me 1 row, with product 1, but quantity = 2, instead of 1. I have tried sub querying the "IN" and multiple other stuff, but nothing has worked. The only solution I have now is to divide SUM(q.quantity_value) by COUNT(n.title), it would work, but I think there is better way to do it :)

Thanks for your help!

Ed


texts: In views, add class depending on the user input in a checkbox.

texts: I need to add a class to a field of views depending if the user wants to have an overlay on the image or no. We need to use a checkbox for the user to input if it needs the class or no.


texts: How to alter default value of select in webform

texts:
Using drupal 7 and Webform (both up2date), how can I alter the default value of a "Select options" field?

I tried to do this:

function mymodul_webform_component_render_alter (&$element, &$component) {
if( $element['#type'] == 'select' &&
      $element['#title'] == 'field1' ) {
$element['#default_value'] = 'bar,foo';}
}

But it's not working...

I can make it work with a single default value if I set the field to "Listbox", what I don't want. But I still can bypass this "if" statement... But still can't set the default value to multiple choices

regards


texts:
Scenario

I have a page which looks like
  http://notfound.stackexchange.com?a=1&b=2

After validation, i use form_set_error to display a drupal error message on the same page(url)
but end up without the url params
  http://notfound.stackexchange.com

Question

Is there a way to preserve/persist the url params on form_set_error ?
Is using drupal_goto the correct way (since i can send the url params again) to redirect to the same page ?
hidden form elements to store the params for use on different pages in the process flow, but as a last resort if there is no other way ?


texts: Forcing a rerun of a module's install script

texts:
I use configuration synchronization to synchronize my different environments, and I enabled Ultimate Cron on my local environment and then ran my sync scripts to synchronize my Staging environment.
My staging environment has Ultimate Cron enabled now, however I can't do anything with it because I keep getting the error:
Base table or view not found: XXXX Table 'my_staging_db.ultimate_cron_log' doesn't exist: INSERT INTO ...

It seems the install script wasn't ran correctly during the sync and so I'm missing the proper tables it creates. Unfortunately this means I can't uninstall the module either, therefore I can't reinstall it. I tried to run drush devel:reinstall ultimate_cron but of course that just runs drush pm:uninstall ultimate_cron so that command fails as well.
The Ultimate Cron's install script contains a hook_schema method defining the schema, so I was hoping there was someway to replicate that method so that I can copy the schema and insert it into the DB so that I can properly uninstall and reinstall the module to get the correct settings.
How can I approach fixing this issue?


texts: Rules- how to perform processing on cancelled accounts?

texts: I have my site configured to allow users to cancel their accounts, in which case the account is blocked and the content is unpublished.  I made a rule to act on the Event after a user account has been deleted, but my actions are not performed when a user cancels his/her account.


texts: Feed import many fields into single content type

texts:
I have a content type that I want to import some sitenames and siteurls from a csv file. So basically create a node type with option to import csv file to fill up field types sitenames and siteurls under one project with feeds or any other solution need help

Setup: Drupal 7, Views 2, Feeds


texts: "Fatal error: Call to a member function setFormClass()"

texts:
I am trying to load the node in an external script, and shows me the following error.

Fatal error: Call to a member function setFormClass() in field_ui_entity_type_build()

The code causing the error is the following one.
define('DRUPAL_DIR', dirname(realpath(dirname(__FILE__))));
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\node\Entity\Node;

$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
$kernel->preHandle($request);

$nid = 123;
$node = Node::load($nid);
$node->set('field_number', 222);
$node->save();

Any help?


texts: Views output realname field as a contextual link

texts:
Contextual is set up to display all content from a user for a specific content type.
www.example.com/users/realname/gallery where realname is contextual filter.
Realname is used with token that reflects field from registration: field-choose-realname.

Lets say we have 2 users and 1st writes "One" as realname and 2nd writes "One Two".
Realname contextual filter is setup to use lowercase and change spaces to dash.

Here is what happens:
www.example.com/users/one/gallery - ok

www.example.com/users/one-two/gallery - page not found error
www.example.com/users/one%20two/gallery - ok

For Contextual "when the filter is in the URL or a default is provided" i am using this php code (i did not write it so i have no clue what it does really):

if (!isset($argument)) {
  return FALSE;
}
$query = db_query('SELECT uid, realname FROM {realname} WHERE realname = :realname', array(':realname' => $argument));
$row = $query->fetchAssoc();
if (isset($row['uid'])) {
  return TRUE;
}
return FALSE;

To better explain what i want to do:
Get sidebar menu like on myspace for bands. When you land on bands page you can use sidebar menu to check their foto galleries, band members, video gallery and links must be made with a field that is not default username (it can be realname module or some other text field). Field validation is used so i do not get same name twice, and all links in pathauto are made example.com/bands/realname.
To repeat again it does work if realname contains 1 word.


texts: How to creat graphs/plots in Drupal, using python library matplotlib, updated in real time if possible?

texts:
I would like to display plots and graphs in Drupal nodes.

Can somebody point out a good workflow to get this done?

Ideally, I would like to use the graphical python library matplotlib. But a solution that is more Drupalish would be fine too.

Ideally, I would like to enter numeric values in an interface, and see a graph updated in real time. I have not been able to discover any module(s) for this.

Jakob


texts: How can I protect the account of the first user, and not allow administration users to alter it?

texts:
I want to not allow users with the permission to administer users to alter the account for the first registered user (the one created during the installation of Drupal).
I also want to not allow them to view the user profile for that user.

Is there a module that allows this?


texts: How do I use custom marker icons with Gmap?

texts:
I want to show markers like on this map here http://demo.symphonythemes.com/drupal7/bizreview/ which are obviously custom.

How do I go about this? I'm either searching for the wrong thing or something.


texts: How do I define the block visibility for content types and term pages?

texts:
I have a block and I want to show it for specific content types and taxonomy terms. There is no common pattern for those pages.

For example, the URLs could be the following ones:

http://example.com/rolling-stones (a taxonomy term page)
http://example.com/drupal/rolling-stones (a Basic node)
http://example.com/rolling-stones-part-1 (an Article node)
http://example.com/demo-content (a Demo node)

I don't want to show the block on the Demo content type, but on nodes of the content types, and term pages, without cloning/replicating the block.

How can I achieve this?


texts:
I am using drupal 6,How can I disable creating new terms during node submit?
Is there any option to do this? I do not see it in vocabulary settings.

I found, that Content taxonomy module have to do it, but I can figure how!
Thank you for your attention


texts:
I have a few external js files that I call in my page, at the moment these are called via script tags in the header.

I am tempted to pull these locally and include them in my themes script file to decrease the load time of the page. I know there is an overhead to keeping the scripts up to date but if it decreases the total load time of the page it may be worth it.

Is there a good practice for this? Should I keep them external or is it good to include them in the drupal JS structure?


texts: How to get the shipping address programmatically in drupal commerce - what wrapper should i use?

texts:
I need to get the shipping address (shipping country to be precise) programmatically in drupal commerce. I have the $order object. How can i get the shipping address?

EDIT - Ok i did this

 $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
 $shipping =  $order_wrapper->commerce_customer_shipping->value();

Now i need to wrap it up again, but i don't know the type

$shipping_wrapper = entity_metadata_wrapper(?, $order);

Whatshould i put instead of the question mark?


texts: Login and get homepage content with a Bash script

texts:
In some developments for drupal 7, I need connect with one user via a bash script then get the content of the connected homepage.

After several searches, my last try :

URL="https://www.mainsite.com/subsiteone/"

curl -s -f -o $output -H "Content-Type:application/xml" --insecure  $URL  -w "@formatsender.conf"  > ./test.txt

formid=$( grep 'input type="hidden" name="form_build_id"' $output | cut -d"=" -f4 | sed -e 's/"//g' | sed -e 's/\/>//g' )
echo $formid #show the good pofm id

curl --request POST ${URL} --data "name=usernameone%26pass=userpasswordone%26form_build_id=$formid%26form_id=user_login"

the last curl shows the content of the login page (not connected) without any error message.
I don't understand where is my mistake..


texts: webform add more module does not show add more button

texts:
I would like public to be able to add records by person name and city.

I enabled the module https://www.drupal.org/project/webform_addmore

I created a webform.

I added a fieldset "Records".

I added 2 text fields: Name, city. I placed the fields under the fieldset.

Edit the fieldset > selected the checkbox "Add More fieldset"

Save

When I go to the webform page as public user, I can see the webform with the fieldset and fields. I do not see the Addmore button. How can I display the addmore buttons to webform fieldset?


texts: How to add taxonomy term reference field in a custom drupal form

texts:
A menu item is defined with drupal_get_form as callback function and returning the form from call back function. How can I add taxonomy_term_reference field to this form?

$items['files/add'] = array(
      'title' => 'Add file',
      'description' => 'Allows users to add files',
      'type' => MENU_CALLBACK,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('mymodule_add_file'),
      'access callback' => TRUE,
    );
function mymodule_add_file($form, &$form_state) {
    drupal_set_title("Add file");
    $form['mymodule_form'] = array(
      '#type' => 'fieldset',
      '#tree' => TRUE,
      '#collapsable' => FALSE,
      '#title' => 'Adding file to locker room',
    );

    $form['mymodule_form']['file'] = array(
      '#type' => 'managed_file',
      '#title' => 'Upload file',
    );

    $form['mymodule_form']['tag'] = array(
      '#type' => 'taxonomy_term_reference',
      '#title' => 'Tags',
    );

    return $form;
}

I am not sure how to add taxonomy_term_reference field for $form['mymodule_form']['tag'] . I want this field to be a text field with auto complete from a vocabulary terms and new term to be added when entered term is not found


texts:
Failed opening required './sites/all/modules/ctools/includes/utility.inc'

But I find utility.inc file already exists in /sites/all/modules/ctools/includes/utility.inc

This error always show up when autocomplete field.


texts: Organic Groups manage members for all but one group role

texts: I have a site that I'm building and planning to use OG to manage access to some content.  There is a requirement for an OG role that is the can manage all memberships, except for one role.  The use case is that the group owners want to delegate membership management in most cases but don't want to allow one of these group admin helpers to be able to change the owners role.  Manage members doesn't provide enough granularity for this.  Any suggestions on how to approach it?


texts: Organic Groups group_access missing from add

texts:
I'm working on a customized commons site. I'm not able to create content for a custom group (e.g.: MyGroup) with the group_access field set to required because it doesn't render in the add content mode, but I still get the message saying "Group visibility field is required". The field doesn't even render, so you can't set the value, but of course, the required property is triggering validation.

Oddly, if I create content and select Group, I can complete the creation of the content, despite the fact that the group_access doesn't even render for that content type either. It makes me wonder what' been customized, but none of the custom modules mention this field.

Note: The group_access field has been added, so it's in the content type's manage fields interface, it's just not showing up in the add new node of that "group/content type".

Any ideas as to what's got to be changed to fix this would be greatly appreciated.
Thx!


texts: How can I move taxonomy terms to a different vocabulary and update term reference fields?

texts:
I need to split a taxonomy vocabulary into two different vocabularies in Drupal 7.

I can use the Taxonomy Manager module to move terms from one vocabulary to another; I have tested this and it works.

However, the big problem is that I have a large number of nodes with a taxonomy term reference field that include references to the terms.

This is what it looks like now:
Nodes of Content Type X have a Taxonomy term reference (multiple values permitted) to Vocabulary A.

This is what I want to do.

Split Vocabulary A into Vocabulary B and Vocabulary A (which contains about half the terms).  [This step can be done with Taxonomy Manager.]
Create a new term reference field to Vocabulary B.  [This can be done from the Field UI.]
Move the term references to terms that are now in Vocabulary B in the Term reference to Vocabulary A to the new term reference for Vocabulary B.  [No idea how to do this except a lot of manual work.]

Any ideas about how to go about step 3?


texts:
I wanted to add link besides editor in add post form that will linked to some static page in the page or it may be link for just some java-script purpose.

Is there any drupal module available to solve this or please suggest how can I proceed to get this done.

-- Thanks for your time


texts: How to enable install from url in Drupal Commons?

texts:
I cannot find any option to install the modules from a url.
Currently, I am installing them through cpanel by manually uploading, unzipping etc.
Can anyone suggest a solution?


texts: Forms - Multiple Checkboxes Default Values Not Populating

texts:
I have a Drupal 7 form using multiple checkboxes. The default value is based on a session variable. However, if I uncheck all of the boxes, I still have a default session variable but it is not populating the correct checkbox in the form. If someone could help point out the bug it would be appreciated:

$types = array('option1'=>'This is Option 1',
                   'option2'=>'This is Option 2');

$form['type'] = array(
    '#title' => t('Type'),
    '#type' => 'checkboxes',
    '#attributes' => array(
      'class' => array(
        'control-box',
        'container-inline'),
        'onClick'=>'this.form.submit();'),
    '#options' => $types,
    '#default_value' => (!empty($_SESSION['type'])) ? $_SESSION['type'] : NULL,
);
drupal_set_message('
'.print_r($_SESSION['type'],true).'
');

This prints out:

Array
(
    [0] => option1
)


texts: Taking over a url and getting variables from url

texts:
I have a (non drupal bound) table, that I need to display within my site.

It has information about "runs":

userID (drupal) - runID - name - distance - ... etc

I want to go to site/run/runID and display the data of that particular run.

I don't know if there is an easy way of doing it without having to create a custom module for it? I basically just need to $get the variables and display them from the database. My first concern is calling my php code when the file is loaded.

And if I need to create a module for it. How would I go about it?

Or perhaps I can use panels to put  my custom code on a page and get the url variables? Or some other module I am not thinking about...

--Update

To get started I created this little module. Now just reading the url parameter runID that is behind it...

function epicrun_menu(){
 $items['epicrun'] = array(
 'page callback' => 'epicrun_my_page',
 'title' => 'Callback',
   'type' => MENU_CALLBACK,
 'access arguments' => array('access content'),
 );
 return $items;
}

* this code (noted in the callback above) creates the
 * contents of the "epicrun" page */

function epicrun_my_page(){
 return "
This is my epicrun demo page.
";
}


texts: Combine Token title with url in an email

texts:
I send emails automatically to users. There is a link in these mails, which points to a node. But I want to use the node title as an alias for this link, so that the link is not directly displayed in the mail.

Currently I use a 'text_format' form element, where I wrote the content of the mail with the corresponding HTML code for the link:

[node:title]

Because this just works with 'full html format', it might be possible to accomplish it in another way?

I would welcome every advise!

Thanks, Daniel


texts: I have given the marketing role the 'create new', 'edit own' and 'delete own' permission for the Article content type however when I log in with that account the 'edit' button doesn't appear on the article page so that user cannot modify the page]1


texts:
I'm new to Drupal.
I want to customize the search module in order to show results from an external JSON.
I was able to insert JSON data in the search page, but now I want to generate a page for each result. Something like blog posts.
I'm using the latest Drupal 6 Version.

Please give me some ideas how can I generate the pages for each Drupal result.

Anticipated thanks!


texts: How to use data in a content type from another content?

texts:
Is it possible to use data in a content type from another content?

I will create a website for a football club. I want to add a content type for clubmembers (approx. 250 members) with personal information.

The members could order clothes from the club through a board member, who will keep the orders per member through a page.

To not have to re-enter some data, is it possible to establish a link with the personal member page? For example, I want to use some fields that are contained in another content type.

If it's possible, how can I do that?


texts: Views Slideshow with jCycle - Making it 100% flexible repsonsive

texts:
Currently I have the following in my views:

Title
Image (size original)

I also currently have my image set at width: 100% via my css file. Now, how do I go about configuring the slideshow to take up 100% width to make the slideshow responsive? I installed the json2.js file to enable the advanced features and I see that there is a "fit" and a "width" option.

Do I set "fit" to 1 or true?

As for the width option, it seem to only take px values only. 100% just gets ignored.

Sure I can go and override this via the css file, but i was wondering if there is a more elegant way of doing it via the provided options in views.


texts: Replace menu item with fontawesome icon without an extra module

texts: I know there are several possibilities to use icons in menus with modules. Is there also a way to replace a menu item link with a fontawesome icon without installing a module? I only need to replace one menu link, so I don't want to use an extra module...


texts: Contextual Filters in a 'Tree-style' View

texts:
I am using the Views Tree Module which allows me to create a View that illustrates parent-child relationships.
My 'associations' go like this:
I have 3 content types which entity-reference each to a single direction.

A Sub task has an EntityReference field pointing to a Main
Task and a Main Task has an EntityReference field pointing
to a Project.
  Subtask -> Main Task -> Project. (associations are done with EntityReference fields)

Now I'd like to embed this view as a block within a given Project's page. Naturally I use a Contextual Filter that uses the ContentID from Url setting.
I thought this would allow me to view within that Project's page the Main Tasks and Sub Tasks that belong to it, but since only the Main Tasks are directly connected with the Project itself only the Main Tasks are shown.

The question:
Is there any way to bring the Subtasks(which belong to the Main Tasks that belong to the given Project) to show as well?

Summary of my project
To sum this up:
I have 3 content types

Project
Main Task
Sub Task

A Subtask entity references a Main Task and this in turn entity
references a Project
I use the Views Tree module to list the Main Tasks and the Subtasks
below each Main Task(in a 'tree-style' view
I want to show this view with the appropriate Main Tasks/Subtasks
inside each Project page.
I use the Views Tree module to construct parent-child relationship
Views


texts: calculate sum of user's orders in drupal commerce

texts: Is there a solution of calculating a sum of user's orders in drupal commerce (7.41 core) and display them in views? I tried to create a table in view which couldn't show anything except total number of orders but had not user filter. What should I do in order to combine "user" and "drupal commerce"?


texts: Problem with Facebook Feed: Warning: file_get_contents(): https:// wrapper is disabled

texts:
I'm having a problem with my Facebook pull feed. It works fine on a development server, but on my live server the block doesn't appear on the page, and I get two php errors, and a single Facebook pull error in my recent logs.

The first php error, which I think is significant is:

Warning: file_get_contents(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in _facebook_pull_feed() (line 280 of /home/phislub9/public_html/sites/all/modules/facebook_pull/facebook_pull.module).

The second php error is related to the first one:

Warning: file_get_contents(https://graph.facebook.com/oauth/access_token?client_id=1392108967676515&client_secret=563ff2dd27ddec75d9b79dc918fe93d4&grant_type=client_credentials): failed to open stream: no suitable wrapper could be found in _facebook_pull_accesstoken() (line 299 of /home/phislub9/public_html/sites/all/modules/facebook_pull/facebook_pull.module)

And the Facebook Pull error doesn't give any diagnostic information beyond that the module isn't working.


texts: Open PDF created with Webform2PDF in a new browser tab

texts:
I have installed the Webform2PDF module and the PDF is created and can be found under the Results tab.

However, I would really need to open the created PDF in a new tab on submission. How can I do that?

I have tried to use hook_form_alter... but I can't figure out quite how to do it. Any suggestion are welcome.

  if($form_id == 'webform_client_form_id'){
    // how to open created PDF after submission
  }


texts: Custom entity form submit handler not being invoked

texts:
I'm trying to attach a submit handler to an entity form (language_delete_form) provided by the ConfigurableLanguage config entity. On the form alter function for that form, the top-level submit handler value looks like $form['#submit'] = ['::submitForm'].

I want to add an additional submission handler, so it looks like $form['#submit'] = ['::submitForm', 'locale_delete_language_submit']. However, locale_delete_language_submit is not being called during the submission process (I would expect it to be invoked after LanguageDeleteForm::submitForm is invoked). What am I missing here?

Based on Berdir's comment here (https://www.drupal.org/project/drupal/issues/2252165#comment-9437863) I would have expected the function to be invoked.

Here's my code:

/**
 * Implements hook_form_FORM_ID_alter() for language_delete_form().
 */
function locale_form_language_delete_form_alter(&$form, FormStateInterface $form_state) {
  $x = 5;
  $form['#submit'][] = 'locale_delete_language_submit';
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function locale_delete_language_submit($form, FormStateInterface $form_state) {
  $defined_value = 'fifty';
}


texts:
I'm trying to switch user session thanks to Drupal Switch. I want to do this so that when I have a certain role, I can switch to another user account to check some data from the user i choose to switch.

My routing :

double_vue.page_double_vue:
    path: '/double-vue'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::doubleVue'
        _title: 'Double vue'
    requirements:
        _permission: 'access content'
double_vue.switched_user:
    path: '/double-vue/{userSwitchedID}'
    defaults:
        _controller: '\Drupal\double_vue\Controller\DoubleVueController::switchUser'
        _title: 'UserSwitched'
    requirements:
        _permission: 'access content'

My view :

switch

My function :

  public function switchUser($userSwitchedID){
    $accountSwitcher = \Drupal::service('account_switcher');
    $account = \Drupal\user\Entity\User::load($userSwitchedID);
    return $accountSwitcher->switchTo($account);
  }

When I click on my to link to switch to another user, I have this error in my logs :

  The controller must return a response
  (Object(Drupal\Core\Session\AccountSwitcher) given)

If I remove the return, I have this :

  The controller must return a response (null given)

How can I fix that so that I can switch to another user account ?


texts: Custom content entity field widget. This value should not be null

texts:
I've created a custom content entity in Drupal 8 and all is well in those regards. I have an issue when I go to create a new record for my entity using the entity form. "This value should not be null.".

The error comes from a widget plugin that I've created that only replicates the functionality of a list of checkboxes that represent taxonomy terms. The field that uses this widget is not a base field, it's added through the UI.
I've looked at the plugin documentation on drupal.org and haven't found much help in regards to my issue.

Below, is my code for the widget form element.

namespace Drupal\my_entity\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\taxonomy\Entity\Term;
use Drupal\user\Entity\User;

/**
 * A widget for displaying terms and supplying an AJAX request when a checkbox is clicked
 *
 * @FieldWidget(
 *   id = "my_entity_programme_areas_lookup_directors",
 *   module = "my_entity",
 *   label = @Translation("Programme Areas Lookup Directors Widget"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class ProgrammeAreasLookupDirectorsWidget extends OptionsWidgetBase
{

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    $value = isset($items[$delta]->value) ? $items[$delta]->value : NULL;

    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element += [
      '#type'          => 'checkboxes',
      '#default_value' => $this->getSelectedOptions($items),
      '#options'       => $this->getOptions($items->getEntity()),
      '#multiple'      => TRUE,
      '#element_validate' => [
        [static::class, 'validate'],
      ],
      '#prefix' => '
',
      '#suffix' => '
',
    ];

    unset($element['#options']['_none']);
    return ['value' => $element];
  }

  /**
    * @inheritdoc
    */
  public static function validate($element, FormStateInterface $form_state) {

    $value = $element['#value'];
    return true;
  }

For the moment, I just want it to pass validation so then I can work on from there, but right now, it can't seem to retrieve a value, even though I can see it has the expected values in the $form_state object (field_programme_areas field).

Any help and tips would be greatly appreciated.
Thanks!


texts: Fill a form on one website and second website automatically grabs it

texts: I have two websites, which have exactly same forms and fields. When the user fills the form on first website, the content gets published on first website. I manually do it on another website. Is there any simpler way of doing this? Is it possible that it automatically grabs the data from 1st website as user fills the form?


texts: How to handle multiple forms' submission in a custom module by clicking on a link

texts:
I have 2 forms in my custom drupal7 module.
The 1st one (mymodule_form1_form) is a normal form with a lot of fields and a submit button at the bottom.
The 2nd one (mymodule_delete_data_form) has 1 hidden field and there is no submit button.
There is a link at the end of the 1st form which triggers a javascript logic. The javascript logic submits the 2nd form.

My problem is that I can't catch the submission of the 2nd form. The page reloads, but it doesn't entry into the mymodule_delete_data_form_submit function and I can't run the special business logic that removes the data from the database in this case.

The 1st form

function mymodule_form1_form($form, &$form_state, $node, $cid)
{
    $form['field1'] = array(
        '#type'       => 'textfield',
        '#title'      => 'Name',
        '#title_display'  => 'invisible',
        '#size'       => 60,
        '#maxlength'  => 128,
        '#required'   => TRUE,
        '#attributes' => array(
            'placeholder' => 'Name',
        )
    );

    $form['delete_record_link'] = array(
        '#markup'     =>
            "

                I would like to delete my record...

",
        '#attributes' => array(
            'class'   => array('additional')
        )
    );

    $form['submit'] = array(
        '#type'  => 'submit',
        '#title' => filter_xss("Submit"),
        '#value' => "Submit",
        '#title_display' => 'invisible'
    );

    return $form;
}

The 2nd form

function mymodule_delete_data_form($form, &$form_state, $node, $cid)
{
    $form['#submit'][] = 'mymodule_delete_data_form_submit';

    $form['delete_record'] = array(
        '#type' => 'textfield',
        '#title' => 'Remove the data from the database',
        '#title_display' => 'invisible',
        '#size' => 60,
        '#maxlength' => 128,
        '#attributes' => array(
            'placeholder' => 'Remove the data from the database',
        ),
        '#value' => "0"
    );

    return $form;
}

The submit function of the 1st form (it works like a charm):

function mymodule_form1_form_submit($form, &$form_state)
{
    echo "submit function 1
";
    exit();
}

The submit function of the 2nd form (it doesn't trigger):

function mymodule_delete_data_form_submit($form, &$form_state)
{
    echo "submit function 2
";
    exit();
}

The javascript logic that submits the 2nd form, when you click on the link in the 1st form:

jQuery(function() {
    var delete_record_field = jQuery("#edit-delete-record");
    var delete_record_link  = jQuery("#mymodule-form1-form .delete-record a");

    delete_record_link.on("click", function() {
        // set the value of the hidden field to 1
        delete_record_field.val("1");

        // submit the form
        jQuery("#mymodule-delete-data-form").submit();
    });
});

What is wrong in my code? How can I catch the submission of the 2nd form?


texts: How do I fix these requirement conflicts?

texts:
While updating through composer, I am getting an error from the Webform module. Drupal version 8.9.1 updated. How do I resolve this error?
Problem 1
    - drupal/webform_node 5.15.0 requires drupal/webform 5.15.0 -> satisfiable by drupal/webform[5.15.0] but these conflict with your requirements or minimum-stability.
    - drupal/webform_node 5.15.0 requires drupal/webform 5.15.0 -> satisfiable by drupal/webform[5.15.0] but these conflict with your requirements or minimum-stability.
    - drupal/webform_node 5.15.0 requires drupal/webform 5.15.0 -> satisfiable by drupal/webform[5.15.0] but these conflict with your requirements or minimum-stability.
    - Installation request for drupal/webform_node (locked at 5.15.0) -> satisfiable by drupal/webform_node[5.15.0].


texts: Upload an image to filesystem, rename it and set it as Profile Picture for current user

texts:
I have the external link of an image where I am trying to:

Upload the image to filesystem.
Rename the image.
Set the owner of the image to current user.
Set the image as Profile Picture for current user.

So far I have:

$full_name = "John Smith";
$picture_url = "https://scontent.fbey14-1.fna.fbcdn.net/v/t31.0-8/14054356_124897527960923_50194821455451882_o.jpg?_nc_cat=106&_nc_sid=09cbfe&_nc_ohc=P4i5oscJf0IAX_KFCfR&_nc_ht=scontent.fbey14-1.fna&oh=c13b6b2d8712db359f3be5e1ec835340&oe=5EF2B1A4";

// Download the picture to local filesystem.
$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

// Get the Profile Pic ID.
$profile_pic_id = $profile_pic->id();

// Load the image.
$picture = \Drupal\file\Entity\File::load($profile_pic_id);

// Rename the image.
$picture->setFilename("$full_name.jpg");
// Set the owner of the profile picture file.
$picture->setOwner($current_user);

// Save the image.
$picture->save();

$current_user->set('user_picture', $profile_pic_id);
$current_user->save();

The image is indeed uploaded to filesystem under public://profile-pictures, also is successfully set as profile picture of the current user.

and the filename of the image at /user/*/edit edit page is set to: john-smith.jpg, however, the filename of the image at public://profile-pictures is 14054356_124897527960923_50194821455451882_o.jpg while I am expecting it to be john-smith.png !

How to rename the image at the filesystem ?

and does $picture->setOwner($current_user) will set the owner of the image to the current user ?


texts: $form_state values show node title instead of integer

texts:
I'm using a select list in my custom module. When I select some option in the list after submitting the form, I can see the $form_state['values']['select_field'] is showing an integer.

How can I make the form_state values to show the title of the list,  instead of number of the selected option?


texts:
How to make the menu like this in drupal 7. There are many customer module in drupal.org, but I don't know much about which module will suit with this. I would to drop down product category when user puts cursor on product menu item.

Thanks


texts: How to create and send an HTML formatted eMail using CSS?

texts:
I am going crazy in making a welcome eMail in Drupal.

What I want is sending a nicely formatted eMail using HTML and CSS. I do not need to send an eMail to user except a welcome eMail after user registration, that's all.

I've tested my code in eMail field in the "Home » Administration » Configuration » People" page, but it does not accept CSS code.

HTML email and mail system modules are so sophisticated that I could not use theme.

Anybody a solution for this?


texts: "Add to Cart" button/from in template (form ID from Node ID)?

texts:
I'm working on a website made with D7 and the Commerce Module, with a "Products" view (for the Product content type) having this relationship field:

(Products referenced by field_info_prodotto) Commerce Product: Add to Cart form

I want this "Buy Now" button/form to also be inside each products' page (= in the template for the Product content type).

I can create a template for single nodes (see code), but how should I edit the general template (node--product-display.tpl.php)?

# node--181.tpl.php
<form class="commerce-add-to-cart commerce-cart-add-to-cart-form-24" autocomplete="off"
action="/en/products" method="post" id="commerce-cart-add-to-cart-form-24" accept-charset="UTF-8">

<input type="hidden" name="product_id" value="24">
<input type="hidden" name="form_id" value="commerce_cart_add_to_cart_form_24">
<input name='form_token' type='hidden' value='<?php print drupal_get_token('commerce_cart_add_to_cart_form_24'); ?>'>

<input type="hidden" name="quantity"
value="1">
<input type="submit" id="edit-submit--9" name="op" value="Add to cart" class="form-submit">

</form>

(In the template there is already the code to show a "Buy Now" field - field_tab_5 - but that's just an empty text field and I suppose it's not what I'm after).