ajax_command_append in Drupal 8 - drupal

I want to display a list of items by ajax on a link click. My link html is
<a class="get-list use-ajax ajax-processed" href="get-my-list">My List</a>
I can do this in Drupal 7 by:
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_append('#my-wrapper', theme('item_list', array('items' => $my_list, 'attributes' => array('class' => array('my-list'))))),
),
);
How to return an ajax callback like this in Drupal 8?

You may want to have a look at the drupal 8 Ajax API (https://api.drupal.org/api/drupal/core!core.api.php/group/ajax/8)
You can define your own callback function or if you have a link you can go to the method of the controller. Here you will have to define an AjaxResponse and put commands in the response.
Here's an example from my project.
The link buildup
$build['ajax-link'] = [
'#title' => '',
'#type' => 'link',
'#id' => 'ajax-link',
'#url' => $url,
'#ajax' => [
'event' => 'click',
'progress' => [
'type' => 'none',
],
],
'#attributes' => [
'class' => [
'fa fa-heart-o fa-2x ' . $activeClass,
],
'title' => 'Ajax heart',
],
];
The controller method it calls
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#ajax-link', $this->subscribeElementGenerator->generateSubscribeElement($event)));
return $response;
The ReplaceCommand just re-generates the link to update it.

Related

Drupal 7 custom module form validate

I'm new to Drupal 7 enviroment. I want to create a custom module form and validate it. I'm facing problems in custom validating the form. Please help. I am providing the code below.
<?php
//implementing hook permissions
function userform_2_permission(){
return array(
'submit userform_2' => array(
'title' => t('Submit Userform_2'),
'description' => t('Submit username in the field'),
),
);
}
// implementing hook menu
function userform_2_menu(){
$items = array();
$items['userform_2'] = array(
'title' => 'Userform 2',
'description' => 'Input the username',
'type' => MENU_NORMAL_ITEM,
'access arguments' => array('access userform_2'),
'page callback' => 'drupal_get_form',
'page arguments' => array('userform_2_form'),
);
return $items;
}
// implementing form
function userform_2_form($form,&$form_state){
$form['username'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#description' => t('Please provide your username'),
'#size' => 60,
'#maxlength' => 128,
);
$form['password'] = array(
'#title' => t('Password'),
'#type' => 'password', // it provdes the password + password_confirm field
'#size' => 60,
'#description' => 'Please provide a password',
'#maxlength' => 128,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Login'),
);
return $form;
}
I want to add form validation here. Please provide the solution for this.
function useform_2_form_validate($form,&$form_state){
// please provide solution
}
// implementing submit handler
function userform_2_form_submit($form, &$form_state){
$u_id = db_insert('userform_2') -> fields(array(
'username' => $form_state['values']['username'],
'password' => $form_state['values']['password'],
)) ->execute();
drupal_set_message(t('the username has been added'));
}
?>
Attach custom validation :
$form['#validate'][] = 'useform_2_form_validate';
But I think if you search a little more you can do it alone ;)
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#validation

Identify form control id in Drupal 7 Forms API

Does form controls in Forms API have id's? Below is my sample code:
function myid_user_page_form(){
$form = array();
$form['id'] = array(
'#type' => 'fieldset',
'#title' => t('ID Information'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['id']['myphoto_button'] = array(
'#type' => 'button',
'#value' => '...',
'#attributes' => array(
'onclick' => "myphoto_options();",),
);
return $form;
}
Sorry for this very simple beginner's question but how to identify my button's id in the sample above(e.g) $form['id']['myphoto_button']?
The #attributes property is used to set html attributes for the element. (Like, id, class, style, onclick, etc.)
I can see that you are using it to bind onclick handler. So, it order to give your button an id:
$form['id']['myphoto_button'] = array(
'#type' => 'button',
'#value' => '...',
'#attributes' => array(
'onclick' => "myphoto_options();",
'id' => 'YOUR-BUTTON-ID',
),
);

Drupal 7 form state undefined index

I create a form like this in .module file:
function form_registration_form($form, &$form_state) {
$form['registration']['email'] = array(
'#title' => t('EMAIL ADDRESS'),
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 44,
'#maxlength' => '80',
'#rules' => array(
'email',
'length[10, 50]',
)
);
$form['registration']['password'] = array(
'#title' => t('PASSWORD'),
'#type' => 'password',
'#required' => TRUE,
'#size' => 44,
'#maxlength' => '80',
);
$form['registration']['submit'] = array(
'#value' => 'SIGN IN',
'#type' => 'submit',
'#submit' => array('form_registration_handler')
);
return $form;
}
function form_registration_handler($form, &$form_state){
$email = $form_state['registration']['email'];
drupal_set_message($email);
}
However drupal always say that "Undefined index: registration in form_registration_form_submit()". I really dont know what I am doing wrong here. Any suggestions will be very useful for me. Thank you very much.
You can always enable the Devel module and dsm($form) the submit function. For instance:
function form_registration_handler($form, &$form_state){
dsm($form);
dsm($form_state);
}
By DSMing, you can easily find the value you want to use in your submit function.
Add this lines to head of your form_registration_form function:
$form = array();
$form['registration'] = array();
The notice appear becuse $form['registration'] is not declared as a void array.

How do I add an onchange handler to a dropdown list in Drupal?

How can I add an onchange handler to a dropdown list in Drupal? The dropdown list is added using hook_form(). I have to perform a function depending on the onchange function.
Is there a way to do this?
You can add a form like this:
hook_form()
{
$form1["dropdown"] = array(
'#type' => 'select',
'#title' => t('Preview the page with themes available'),
'#options' => $ptions,
'#default_value' => 'defalut_value',
'#attributes' => array('onchange' => "form.submit('dropdown')"),
);
//Submit button:
$form1['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit '),
'#attributes' => array('style' => 'display: none;'),
);
Now you can add submit functionality using hook_submit().
Here is the simple example using '#ajax' property
$form['select'] = array(
'#type' => 'select',
'#title' => 'Option #1',
'#options' => $option,
'#ajax' => array(
// Call function that rebuilt other field
'callback' => 'ajax_load_field',
'method' => 'replace',
// div to be get replace by function output
'wrapper' => 'chart',
'effect' => 'fade'
),
);
If you generate another form field by using this drop down.
Then use AHAH for that.
$form['my_form_submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#weight' => 1,
'#submit' => array('my_form_submit'),//none JS version
'#ahah' => array(
'event' => 'click',
'path' => 'mymodule/js', //Your ajax function path
'wrapper' => 'myform-wrapper',
'method' => 'replace',
'effect' => 'fade',
'progress' => array(
'type' => 'bar',
'message' => t('Loading...')
)
),
While I am sure that Nicholas is way past this issue by now, this may help some who are searching for a solution.
I'm using D7 and getting the single quotes around dropdown encoded to ' I suppose by >check_plain. >How do I avoid that? – Nicholas Tolley Cottrell Jun 2 at 16:03
I just found the "Drupal" way of doing this.
Step 1, set a variable to contain dropdown by using drupal_add_js:
drupal_add_js(array('mymodule' => array('varname' => 'dropdown')), 'setting');
Step 2, add the attributes line as
'#attributes' => array('onchange' => "form.submit(Drupal.settings.mymodule.varname)"),

Correct way to use Drupal 7 Entities and Field API

I'm trying to use Drupal 7's entities and field API to correctly build a new module. What I have been unable to understand from the documentation is the correct way to use the new API to create a 'content type' (not a node type) with a number of set fields, such as Body.
I'm trying to set up the entity using hook_entity_info, then I believe I need to add the body field using field_create_instance, but I can't seem to get it to work.
In mycontenttype.module:
/**
* Implements hook_entity_info().
*/
function mycontenttype_entity_info() {
$return = array(
'mycontenttype' => array(
'label' => t('My Content Type'),
'controller class' => 'MyContentTypeEntityController',
'base table' => 'content_type',
'uri callback' => 'content_type_uri',
'entity keys' => array(
'id' => 'cid',
'label' => 'title',
),
'bundles' => array(
'mycontenttype' => array(
'label' => 'My Content Type',
'admin' => array(
'path' => 'admin/contenttype',
'access arguments' => array('administer contenttype'),
),
),
),
'fieldable' => true,
),
);
return $return;
}
/**
* Implements hook_field_extra_fields().
*/
function mycontenttype_field_extra_fields() {
$return['mycontenttype']['mycontenttype'] = array(
'form' => array(
'body' => array(
'label' => 'Body',
'description' => t('Body content'),
'weight' => 0,
),
),
);
return $return;
}
Then does this go in the .install file?
function mycontenttype_install() {
$field = array(
'field_name' => 'body',
'type' => 'text_with_summary',
'entity_types' => array('survey'),
'translatable' => TRUE,
);
field_create_field($field);
$instance = array(
'entity_type' => 'mycontenttype',
'field_name' => 'body',
'bundle' => 'mycontenttype',
'label' => 'Body',
'widget_type' => 'text_textarea_with_summary',
'settings' => array('display_summary' => TRUE),
'display' => array(
'default' => array(
'label' => 'hidden',
'type' => 'text_default',
),
'teaser' => array(
'label' => 'hidden',
'type' => 'text_summary_or_trimmed',
),
),
);
field_create_instance($instance);
}
I think your problem is that if node module is installed, there is already a field named 'body'. You should either re-name your field to something like 'mycontenttype_body' (comment.module uses comment_body), or re-use the 'body' field and skip the adding the field part and skip to adding the instance of it. The former is recommended over the latter.
Every field has an array property, entity_types, which limits the entities to which the field can be attached.
The best Drupal solution I can find, hook_field_create_field, can alter fields as they are created, but that's no good for the body field which is created on installation.
So my solution is just to edit the database directly in my hook_install
$data_col = db_query("SELECT data from field_config where field_name = 'body'")->fetchAssoc();
$data = unserialize($data_col['data']);
$data['entity_types'][] = 'MY_ENTITY_TYPE';
db_update('field_config')
->fields(array('data' => array('data' => serialize($data))))
->condition('field_name', 'body')
->execute();
just started down the same path here is a video from fago
Here's a nice repo to start: Lawmakers entity

Resources