Drupal 8 form builder error webform custom module - drupal

can anyone guide me , I'm continuously facing this error , webform custom module Drupal 8
InvalidArgumentException: The form argument sun_webforms_usage_settings_page_form is not a valid form. in Drupal\Core\Form\FormBuilder->getFormId() (line 197 of F:\wamp\www\neo9\web\core\lib\Drupal\Core\Form\FormBuilder.php).
function neo_webforms_usage_settings_page_form($form, \Drupal\Core\Form\FormStateInterface $form_state)
{
$form = array();
$form['neo_webforms_usage_inactivity_time'] = array(
'#title' => t('Inactivity Time (seconds)'),
'#type' => 'textfield',
'#default_value' => \Drupal::state()->get('neo_webforms_usage_inactivity_time', 86400),
);
$form['neo_webforms_usage_alert_email'] = array(
'#title' => t('Alert receiver email (one per line).'),
'#type' => 'textarea',
'#default_value' => \Drupal::state()->get('neo_webforms_usage_alert_email', ""),
);
return system_settings_form($form);
}
and Controller
public function neo_webforms_usage_settings_page() {
$header = [
'#type' => 'markup',
'#markup' => t('<h4>Webform Usage Settings</h4>'),
];
$form = \Drupal::formBuilder()->getForm('neo_webforms_usage_settings_page_form');
$page = [
'header' => $header,
'form' => $form,
];
return $page;
}
}
Please anyone help me with that?

As per the official documentation of the FormBuilder getForm function, the parameter of getForm should be the Class/Instance name of the Form.
Parameters
\Drupal\Core\Form\FormInterface|string $form_arg: The value must be one of the following: The name of a class that implements \Drupal\Core\Form\FormInterface.
An instance of a class that implements \Drupal\Core\Form\FormInterface.
Try passing something like this:
$form = \Drupal::formBuilder()->getForm('\Drupal\module_name\Form\FormClassName');

Related

Drupal 7: Insert into content type from custom module function

I created a form inside a custom module, in a drupal 7 project, and I need to insert the values into a custom content type called 'players'
Here is what I have for a form:
function custom_module_reg_form($form, $form_state){
$form['first_name'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('First Name')),
);
$form['last_name'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Last Name')),
);
$form['email_address'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Email Address')),
);
$form['state'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('State')),
);
$form['zip_code'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Zip Code')),
);
$form['phone_number'] = array(
'#type' => 'textfield',
'#attributes' => array('placeholder' => t('Phone Number')),
);
$form['password'] = array(
'#type' => 'password',
'#attributes' => array('placeholder' => t('Password')),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Register',
);
return $form;
}
Here is the submit function but I am getting an error:
function custom_module_reg_form_submit($form, $form_state){
$first_name = $form_state['values']['first_name'];
$last_name = $form_state['values']['last_name'];
$email_address = $form_state['values']['email_address'];
$state = $form_state['values']['state'];
$zip_code = $form_state['values']['zip_code'];
$phone_number = $form_state['values']['phone_number'];
$password = encrypt($form_state['values']['password']);
$nid = db_insert('players')->fields(array(
'first_name' => $first_name,
'last_name' => $last_name,
'email_address' => $email_address,
'state' => $state,
'zip_code' => $zip_code,
'phone_number' => $phone_number,
'password' => $password,
'created' => REQUEST_TIME
))->execute();
// Save new node
$node = new stdClass();
// Set node title
$node->title = $email_address;
// set node type ex: article etc
$node->type = "players";
// set node language
$node->language = LANGUAGE_NONE;
//(1 or 0): published or not
$node->status = 0;
//(1 or 0): promoted to front page
$node->promote = 0;
node_object_prepare($node);
node_save($node);
}
I was following an example and I see in my logs that the table is not correct but I can't find anywhere else that gives an example. What am I doing wrong? Is it better to create a custom table for programmatically inserting from forms? Thanks and please let me know.
There are two common ways of programmatically creating nodes in Drupal 7: without or with the Entity API contributed module.
Without Entity API
$node = new stdClass();
$node->type = "players";
$node->uid = $user->uid; // makes sense to have the global $user the owner of the node
$node->language = LANGUAGE_NONE;
$node->status = 0;
$node->promote = 0;
$node->title = $email_address;
// NB: if you created the field in Drupal's UI -- it will be named "field_first_name", not "first_name"
$node->field_first_name[$node->language][]['value'] = $first_name;
// ...
$node = node_submit($node);
node_save($node);
With Entity API (more common nowadays)
// Use the Entity API to create a new object
$values = array(
'type' => 'players',
'uid' => $user->uid,
'status' => 1,
'promote' => 0,
);
$entity = entity_create('node', $values);
// Then create an entity_metadata_wrapper around the new entity.
$wrapper = entity_metadata_wrapper('node', $entity);
// Now assign values through the wrapper.
$wrapper->title->set($email_address);
$wrapper->field_first_name->set($first_name);
// ...
// Finally save the node.
$wrapper->save();
Whichever way you choose, you do not need db_insert('players'). It actually won't work, because Drupal 7 does not store the entity in a single database table.
More information about creating nodes in code can be found here.

How do I create a content type from SQL query?

<?php
function customtable_permission() {
return array(
'show people' => array(
'title' => t('List of people'),
'description' => t('The table'),
),
);
}
function customtable_menu() {
$items = array();
$items['people'] = array(
'type' => MENU_NORMAL_ITEM,
'title' => t('Title'),
'description' => 'This page should show a table from a remote DB',
'page callback' => 'customtable_db_data',
'access arguments' => array('show people'),
);
return $items;
}
function customtable_db_data() {
db_set_active('remote_database');
$results = db_query("SELECT * FROM {people}");
$header = array(t('Id'), t('Name'), t('Department'), t('Division'), t('Insurance'));
$rows = array();
foreach($results AS $result) {
$rows[] = array(
$result->id,
$result->name,
$result->department,
$result->division,
$result->insurance,
);
}
db_set_active('default');
return theme('table', array('header'=> $header, 'rows' => $rows));
}
?>
This all works fine and I can go to site.com/people and see the all the entries from the database printed nicely in a table
But I want text boxes where I can filter each column. Users can search by name or a specific insurance or department. I think it is possible programmatically, but I'd like to know if there is a more "drupal" approach. Content types have the ability to filter its fields. Am I to create a content type based on my query? I don't exactly know. Any assist is appreciated.
I think the best way to do this is migrate the query result to a drupal content type, to do this you need to use the migrate api.
-Install and enabled migrate and migrate_ui drupal modules.
-Create any content type you want with your fields.Using the drupal interface.
-Create a custom module, using migrate api. For example:
/sites/all/modules/custom/migrate_customtable/migrate_customtable.migrate.inc
function migrate_customtable_migrate_api() {
$api = array(
'api' => 2,
'groups' => array(
'custom_table' => array(
'title' => t('Custom Table'),
),
),
'migrations' => array(
'Projects' => array(
'class_name' => 'CustomTableMigration',
'group_name' => 'custom_table',
'event_log' => ''
),
),
);
return $api;
}
Then, create a class called: CustomTableMigration.inc that will contains the migration:
<?php
/**
* Created by PhpStorm.
* User: ldcontreras
* Date: 25/07/18
* Time: 10:13
*/
class CustomTableMigration extends Migration {
public function __construct($arguments) {
parent::__construct($arguments);
$query = Database::getConnection('default', 'migrate_custom_table')//this must be define in your settins.php file
->select('people')
->fields('productos_new', array(
'id',
'name',
'department',
'division',
'insurance',
)
);
$this->source = new MigrateSourceSQL($query, array(), NULL, array(map_joinable => FALSE));
$this->destination = new MigrateDestinationNode('content_type_machine_name'); //the content type created
$this->map = new MigrateSQLMap($this->machineName,
array(
'id' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'description' => t('Source ID'),
)
),
MigrateDestinationNode::getKeySchema()
);
$this->addFieldMapping('title', 'name');
$this->addFieldMapping('field_department_content_type', 'department');
$this->addFieldMapping('field_division_content_type', 'division');
$this->addFieldMapping('field_insurance_content_type', 'insurance');
$this->addUnmigratedDestinations(array(
'body:format',
'comment',
'is_new',
'log',
'promote',
'revision',
'revision_uid',
'tnid',
'totalcount',
'daycount',
'timestamp',
'path',
'translate',
'sticky',
'uid',
));
}
}
Finally,enable your custom module and run the migration using drush.

drupal field widget not saving submitted data

I'm trying to create a custom widget but when I submit, Drupal doesn't seem to save any data. When using hook_field_attach_submit() to display what data I've pasted, it is listed as null.
Strangely, if i change the #type to be a single textfield instead of a fieldset it will save only the first character of the string that has been entered.
This seems like a validation issue, but I'm not sure how to hook into it or to debug the problem. Where can I go from here?
<?php
function guide_field_widget_info(){
dpm("guide_field_widget_info");
return array(
'guide_text_textfield' => array(
'label' => t('test Text field'),
'field types' => array('text'),
'settings' => array('size' => 60),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_CUSTOM,
'default value' => FIELD_BEHAVIOR_DEFAULT,
),
)
);
}
function guide_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$field_name = $instance['field_name'];
$required = $element['#required'];
$item =& $items[$delta];
$element += array(
'#type' => 'fieldset',
'#title' => t('helloooooooo'),
);
$required = $element['#required'];
$item =& $items[$delta];
$element['nametest'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => $required,
// use #default_value to prepopulate the element
// with the current saved value
'#default_value' => isset($item['nametest']) ? $item['nametest'] : '',
);
$element['checkme'] = array(
'#title' => t('Check this box or dont'),
'#type' => 'checkbox',
'#default_value' => isset($item['checkme']) ? $item['checkme'] : '',
);
//When changing the above code to have a single field, $value is no longer null but will display the first character of the string. I've pasted the code I used to test beloe
/*
$element+= array(
'#title' => t('Name'),
'#type' => 'textfield',
'#default_value' => isset($item['nametest']) ? $item['nametest'] : '',
);
*/
return $element;
}
//hooking this here is required given that after submit, the value is a multidimensional array, whereas the expected value of text is, well, text :-)
function guide_field_attach_submit($entity_type, $entity, $form, &$form_state){
dpm($form,"guide_field_attach_submit data"); //shows $form[field_test_field][und][0] [value] as being null
}
hook_field_is_empty is mandatory and has to be implement like following:
/**
* Implements hook_field_is_empty().
*/
function MODULENAME_field_is_empty($item, $field) {
if ($field['type'] == 'FIELDTYPE') {
if (empty($item[$field['type']]['YourField']) ) {
return (TRUE);
}
}
return (FALSE);
}

Warning: Missing argument 2 for customvishal_form() in Drupal 7 :

I have made a custom module and it works fine till I start working on my custom theme.
Once I move over to my custom theme I get this error
Warning: Missing argument 2 for customvishal_form(), called in
/home/vishal/Dropbox/sites/new/includes/theme.inc on line 1029 and
defined in customvishal_form() (line 441 of
/home/vishal/Dropbox/sites/new/sites/all/modules/customvishal/customvishal.module).
You can see the error at : http://www.iamvishal.com/dev/about-us
I don't think anything is wrong with my code :
/**
* A simple form.
*/
function customvishal_form($form, &$form_submit) {
$form['customvishalactivate'] = array(
'#title' => t('Activate Preference'),
'#type' => 'radios',
'#options' => array('1' => t('Yes'), '0' => t('No')),
'#required' => TRUE,
);
return $form;
}
Its called from
function customvishal_pref($arg1)
{
// Here we willl make the form and save the data so when cron
// runs we will check the users preference
$build = array(
'header_text' => array(
'#type' => 'markup',
'#markup' => '<p>' . t('This page is where you add your preferences. Based on your
entered choices we will send you alerts ') . '</p>',
),
'example_form' => drupal_get_form('customvishal_form'),
);
return $build;
}
What might be causing this problem ?
Cheers,
Vishal
I had the same issue
I called hook_form like this:
/**
* Implements of hook_menu().
*/
function skupina_menu() {
$items = array();
$items['admin/config/people/skupina'] = array(
'title' => 'Skupiny odborníkov',
'description' => 'Prehľady návštev odborníkov',
'page callback' => 'drupal_get_form',
'page arguments' => array('skupina_statistics'),
'access arguments' => array('view statistics'),
'file' => 'admin.inc',
'file path' => drupal_get_path('module', 'skupina'),
'weight' => 1,
);
return $items;
}
and then
/**
* Prehlad navstev odbornikov - page
*/
function skupina_statistics($form, &$form_state) {
$form = array();
$form['skupina_obdobie'] = array(
'#type' => 'select',
'#title' => t('Zmeniť zobrazenie'),
'#options' => skupina_get_zobrazenia(),
'#description' => t('Zmení filtrovanie dát podľa zvolenej možnosti.'),
'#required' => FALSE,
);
return $form;
}
my problem was, that the function didn't have the "_form" in its name so its produce those warnings.
So the function must be called "skupina_statistics_form in my case
when the form function is called the only parameter that is sent to it is the form variable. Since your second function parameter doesn't have a default value it obviously produces a warning.
If you never use it in the function code you might consider removing it or providing a default value.
e.g.:
function customvishal_form($form, &$form_submit = NULL)
or you might consider passing an additional parameter. You can do this like so:
drupal_get_form('customvishal_form', $some_your_parameter);
I think I know the answer. I had the exact same problem.
Is your module named exactly as your custom theme? Mine was and I changed my theme name and the error went away

Drupal AHAH, Dynamic form expansion

Form
$form['animal'] = array(
'#type' => 'select',
'#title' => t('Animal'),
'#options' => load_animals(),
'#ahah' => array(
'event' => 'change',
'path' => 'path/to/ajax/service',
'method' => 'replace',
'effect' => 'fade',
'wrapper' => 'breed-wrapper',
),
);
...
$form['breed'] = array(
'#type' => 'select',
'#title' => t('Breeds'),
'#options' => array('Select animal to load breed'),
'#prefix' => '<div id="breed-wrapper">',
'#suffix' => '</div>',
);
And following is the AHAH callback processing
$post = $_POST;
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form_build_id = $post['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form['#redirect'] = FALSE;
$form['#post'] = $post;
$form['#programmed'] = FALSE;
$form_state['post'] = $post;
drupal_process_form($form_id, $form, $form_state);
// New form elements
$breed_form = $form['breed'];
$options = load_breeds((int)$post['animal']);
$breed_form['#options'] = $options;
$form['breed'] = $breed_form;
form_set_cache($form_build_id, $form, $form_state);
$form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
unset($breed_form['#prefix'], $breed_form['#suffix']);
// Render the new output.
$output .= drupal_render($breed_form);
drupal_json(array('status' => TRUE, 'data' => $output));
Default form submit handler
function default_form_submit(&$form, $form_state){
$clicked_button = $form_state['clicked_button']['#value'];
$values = $form_state['values'];
if($clicked_button == $values['submit']){
unset($values['op'], $values['submit'], $values['form_build_id'],
$values['form_token'], $values['form_id']);
....
drupal_goto($_REQUEST['q'], $query);
}
}
When I finally submit the form in normal post way, a validation error is reported as An illegal choice has been detected. Am I properly using form_set_cache()?
On AHAH post, the default form submission handler is also invoked. As this handler contains a redirection logic so AHAH request is collapsed. How to bypass it even-though I am doing click_button validation?
i think for your last question, use need to set $form_state['ahah_submission'] = TRUE.

Resources