Symfony ChoiceType with big array, error 'This value is not valid.' - arrays

I have a form with a ChoiceType. Values are set with a Ajax request (this choice depends of an other choice).
But there is many choices (13200), And when I submit the the form whith a correct choice, I have this error "This value is not valid.".
I have tried whith 100 choices, and it's work well.
This form is build whith EventsListener (simplified version) :
$ff = $builder->getFormFactory();
// function to add 'template' choice field dynamically
$func = function ( \Symfony\Component\Form\FormEvent $e) use ($ff, $curlRequest, $builder, $rapport) {
$data = $e->getData();
$form = $e->getForm();
if ($form->has('idsSouscripteur') )
{
$form->remove('idsSouscripteur');
}
$idClient = $data->getIdClient() > 0 ? $data->getIdClient() : null;
$idsSouscripteur = count($data->getIdsSouscripteur()) > 0 ? $data->getIdsSouscripteur() : null;
$souscripteursArray = [];
if (!is_null($idClient)) {
$souscripteurs = /* Request to get 'souscripteurs' objects */;
foreach ($souscripteurs as $souscripteur) {
$souscripteursArray[$souscripteur->nomSouscripteur] = $souscripteur->numInterne;
}
}
$form
->add('idsSouscripteur', ChoiceType::class, [
'label' => 'rapports.block_2.souscripteur',
'mapped' => false,
'multiple' => true,
'choices' => $souscripteursArray,
'constraints' => array(
new NotBlank()
),
'attr' => [
'placeholder' => 'rapports.block_2.souscripteur_placeholder'
]
]);
if (!is_null($idsSouscripteur)) {
$rapport->setIdsSouscripteur($idsSouscripteur);
}
};
// Register the function above as EventListener on PreSet and PreBind
$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
$builder->addEventListener(FormEvents::PRE_SUBMIT, $func);
Anyone lnow why symfony is not working with big array ?

Related

Codeigniter Insert Array to Database

I have created a form in Codeigniter with a phone number field that dynamically is duplicated using javascript. So basically I can have one or more fields like this.
<input name="phone[]" value=""type="text">
<input name="phone[]" value=""type="text">
Then in my controller I have
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $this->input->post('phone[]')
);
Then I am saving this to my dabase like so
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
but obviously the code for 'phone' is wrong, I just cant figure out how to properly do this.
you can't save array in to database. You can convert it in to string using implode() and whenever you needed then convert it back in array using explode(). Like below
$phone=implode(',',$this->input->post('phone'));
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone
);
OR
You can convert it to json string and when you needed convert back to Array Like below:
$phone = json_encode($this->input->post('phone'));
Convert back to array
$phone = json_decode($phone, TRUE);
Modify your function as below and it will works like charm,
function SaveForm($form_data)
{
foreach ($form_data as $contact)
{
$data[] = array(
'first_name' => $contact['first_name'],
'last_name' => $contact['last_name'],
'phone' => $contact['phone']
);
}
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
Modified:
Oh, yes you have to edit para array that you passed to SaveForm function.
Please use following code, ignore above code:
foreach($_POST['first_name'] as $key=>$fname)
{
$form_data[] = array(
'first_name' => $_POST['first_name'][$key],
'last_name' => $_POST['last_name'][$key],
'phone' => $_POST['phone'][$key],
);
}
function SaveForm($form_data)
{
$this->db->insert_batch('customers', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
return FALSE;
}
In controller
$phone = $_POST['phone'];//this will store data as array. Check image 02
$form_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'phone' => $phone,//some times it works with '$phone'
);
In Model
function SaveForm($form_data)
{
$this->db->insert('customers', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
else
{
return FALSE;
}
}
Tested
Image 01 (My form)
Image 02 (After Submitted)
mysql doesn’t has any array data type. So we can not store array directly into mysql database.
To do this we have to first convert array into string using php serialize() function then save it into mysql database.
for eg:php code to store array in database
$array = array("foo", "bar", "hello", "world");
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$array_string=mysql_escape_string(serialize($array));
To retrieve array from database
$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db("mysql_db",$conn);
$q=mysql_query("select column from table",$conn);
while($rs=mysql_fetch_assoc($q))
{
$array= unserialize($rs['column']);
print_r($array);
}
for array insertion to database use this programme in codeigniter controller=>
$inputdata=$this->input->post();
$phone=array($inputdata['phone']);
foreach($phone as $arr)
{
$phoneNo=$arr;
$f=count($phoneNo);
for($i=0;$i<$f;$i++)
{
$arre=[
'phone'=>$phoneNo[$i],
];
$insertB= $this->user_model->userdata($arre);
}
}
public function add_theme_pages(){
$page_name = $this->input->post('page');
$page_img = $this->input->post('page_img');
for($i=0; $i < count($page_name); $i++){
$pages_data = array(
'theme_id' => $this->input->post('theme_id'),
'theme_page_name' => $page_name[$i],
'theme_page_img' => $page_img[$i]
);
if($this->backendM->add_theme_pages($pages_data)){
$this->session->set_flashdata('message', 'Theme Added Successfully !');
$this->session->set_flashdata('message_class', 'green');
$this->create_template();
}else{
$this->create_template();
}
}
}

Drupal 7 create and send mailchimp campaign programmatically

How to create and send mailchimp campaign programmatically in drupal 7 ?
function kf_mailchimp_create_campaign() {
if (!isset($_GET['cron_key']) || ($_GET['cron_key'] != 'kQ7kOy4uRgPJd1FX1QQAERPeSYuPjp1qBW65goYcbDQ')) {
watchdog('kf_mailchimp', 'Invalid cron key !cron_key has been used to create campaign.', array('!cron_key' => $_GET['cron_key']));
drupal_exit();
}
$data['site_url'] = url('<front>', array('absolute' => TRUE));
$data['site_logo'] = theme_image(array(
'path' => drupal_get_path('theme', 'knackforge') . '/logo.png',
'alt' => 'KnackForge',
'attributes' => array('border' => 0),
));
$options = array(
'list_id' => $mc_list_id, // Change this to match list id from mailchimp.com.
'from_email' => variable_get('site_mail'),
'from_name' => 'KnackForge',
'to_email' => variable_get('site_name')
);
$type = 'regular';
$q = mailchimp_get_api_object(); // Make sure a list has been created in your drupal site.
$results = views_get_view_result('deal_mailchimp', 'page');
// Check to prevent sending empty newsletter
if (empty($results)) {
watchdog('kf_mailchimp', 'No active deals to send for today');
drupal_exit();
}
$data['deals'] = views_embed_view('deal_mailchimp', 'page');
$content = array(
'html' => theme('kf_mailchimp', $data),
);
$options['subject'] = t('Newsletter');
$options['title'] = $options['subject'] . ' - ' . date('r');
$options['tracking'] = array(
'opens' => TRUE,
'html_clicks' => TRUE,
'text_clicks' => TRUE
);
$options['authenticate'] = false;
$options['analytics'] = array('google'=>'atphga');
$cid = $q->campaignCreate($type, $options, $content);
watchdog('kf_mailchimp', 'Created campaign');
$result = $q->campaignSendNow($cid);
watchdog('kf_mailchimp', 'campaignSendNow() response !result', array('!result' => '<pre>' . print_r($result, 1) . '</pre>'));

hook_block_view not passing information

I am trying to build my first custom module in Drupal 7. It is a block form for the user to search a DB table for customer information. I've created both the module and info files. My module appears under the modules and blocks section, but when I add the block to Content, the subject and content aren't being passed from my hook_block_view. So, instead of the form being displayed, it just shows the block title and body. Can someone tell me what I'm missing?
<?php
/**
*#file
*
*/
/** Implements hook_block_info().
*
*/
function searchEngine_block_info(){
$blocks = array();
$blocks['searchEngine_form'] = array (
'info' => t("Applicant Search"),
'cache' => DRUPAL_CACHE_GLOBAL,
);
return $blocks;
}
/** Implements hook_block_view().
*
*/
function searchEngine_block_view($delta = ''){
$block = array();
switch($delta) {
case 'searchEngine_form':
$block['subject'] = t('Applicant Search');
$block['content'] = drupal_get_form('searchEngine_form');
break;
}
return $block;
}
function searchEngine_form($form, &$form_state) {
$form['searchOptions'] = array(
'#type' => 'select',
'#title' => t("Select how you would like to search for an applicant."),
'#default_value'=> variable_get("gwf", true),
'#options' => array(
'gwf' => "GWF".t(" Number"),
'email' => t("Email"),
'name' => t("Name"),
'phone_number' => t("Phone Number"),
),
);
$form['data'] = array(
'#type' => 'textfeild',
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function searchEngine_submit($form, $form_state) {
if(isset($form['data'])){
if($form['searchOptions'] == "name"){
$name = preg_split("/[\s,]+/", $form['data']);
$result = db_query('SELECT * FROM tls_active_applicants WHERE first_name = '.$name['0'].' AND last_name = '.$name['1']);
}else{
$result = db_query('SELECT * FROM tls_active_applicants WHERE '.$form['searchOptions'].' = '.$form['data']);
}
print_r($result);
}
}
Passing a renderable array here is fine:
$block['content'] = drupal_get_form('searchEngine_form');
I've just tested your code and the form appears fine for me:
Now we know the code works it makes me wonder if it is just some css or something hiding it?
I would also install the devel module as it will help with debugging.
The you could use this code:
function searchEngine_block_view($delta = ''){
$block = array();
switch($delta) {
case 'searchEngine_form':
$block['subject'] = t('Applicant Search');
$form = drupal_get_form('test_form');
dpm($form); // call to dpm here to log if you are successfully getting the form at this point
$block['content'] = $form;
break;
}
return $block;
}

Populating #options, #header for tableselect in ajax callback function

What I am trying to do is display a table with checkboxes on the press of a button by ajax. The table should be initially hidden and get populated on the fly by a function call.
If initially I load $options1 with some dummy values , then after ajax call it throws in an error saying-
Notice: Undefined index: red in theme_tableselect() (line 3285 of
D:\wamp\www\drupal7\includes\form.inc).
where 'red' is the index of a dummy row value and #options don't get populated with the new values. What is the way to get this working ?
Here is the code for the form-
$form['mltag_new']['tag'] = array(
'#type' => 'button',
'#value' => t("Suggest Tags"),
'#ajax' => array(
'callback' => 'mltag_suggest_tags_ajax',
'wrapper' => 'mltag_suggest_tags_table_div',
'effect' => 'slide',
),
);
$options1 = array(); //initial dummy values
$options1['red']['tag'] = "A red row";
$options1['red']['chi'] = "A red row";
$form['mltag_new']['myselector'] = array (
'#type' => 'tableselect',
'#title' => 'My Selector',
'#header' => $header,
'#options' => $options1,
'#prefix' => '<div id="mltag_suggest_tags_table_div">',
'#suffix' => '</div>',
);
return $form;
and the Ajax callback looks something like this-
function mltag_suggest_tags_ajax($form, $form_state) {
//$content has some content
//pass the content to a function
include_once 'includes/content_tag.inc';
$tags = mltag_content_tag($content, variable_get('algo_type'), 20);
if (empty($tags)) {
$output .= t('Content is insufficient to generate Tags using this algorithm. <br>Please choose other algorithm from Settings Page.');
$form['mltag_new']['sample_text']['#markup'] = $output;
return $form['mltag_new']['sample_text'];
}
else {
$algo = variable_get('algo_type');
if ($algo == 1) {
$header = array(
'tag' => t('Tag'),
'frequency' => t('Frequency'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'frequency' => $value,
);
}
}
elseif ($algo == 2) {
$header = array(
'tag' => t('Tag'),
'chi' => t('Chi Square Value'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'chi' => $value,
);
}
}
$form['mltag_new']['myselector']['#header'] = $header;
$form['mltag_new']['myselector']['#options'] = $options;
return $form['mltag_new']['myselector'];
}
}
I replied to your post on Drupal.org about how I'm working on a somewhat similar problem. Try adding
$form['mltag_new']['myselector'] =
form_process_tableselect($form['mltag_new']['myselector']);
just before your return. Hopefully that helps you more than it did me. Beware that the #options just get rendered when the block reloads from the ajax, but the original $form object doesn't seem to be aware.
I know that this is a few years later, but I found this while searching for my own solution:
The tableselect module creates checkboxes in the $ form that have to be removed. in the example above, they would be in $form['mltag_new']['myselector'] with keys equal to the original $option1 in your original code. If you unset those, then call
$form['mltag_new']['myselector'] = form_process_tableselect($form['mltag_new']['myselector']);
before your return, it will eliminate the dummy rows.

Themeless Page - Or a content-only content type

I need to create content that only outputs what I entered, no layout, no comments, blocks, etc.
If I could implement a custom content type that used blank templates that might work, but I've been unable to make it work so far as overriding the themes seems to replace everything site-wide. So, skipping that, is there a simple way I'm not aware of, to just output what I type in the content's body, with no layout/blocks/comments,etc.
Is it possible via a custom module to add a custom field at the bottom, and then during the process_page() hook, ignore the theming and layout and just output the content?
Please don't suggest "Views" as it's not stable.
Some example use cases:
A page that's a PHP type, and it's simply a script that I don't want layout as an example.
Or if I have some json data to return.
Or if I want to toss up a all-in-one page with it's own theme.
Any suggestions?
I am working on a module that will do this and also integrate with views so you can set a view to be "theme-less" as well. I have it so that it will create a checkbox on a node form that you can specify the node to be theme-less node. Once that is checked, the node will be displayed with no theme (the content only, no title).
It's a little hackish, but it works preliminarily. I will be fleshing this out as I have need for it and I will likely also integrate it with views over time.
timeless.install
<?php
/**
* themeless.install
* defines our schema for flagging nodes as being themeless or not.
*/
function themeless_schema() {
$schema['themeless_node'] = array(
'description' => 'Keeps track of which nodes are themeless.',
'fields' => array(
'nid' => array(
'description' => 'The node id of a themeless node',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'primary_key' => array('nid'),
);
return $schema;
}
function themeless_enable() {
if (db_table_exists('themeless_node') == FALSE) {
drupal_install_schema('themeless');
}
}
function themeless_uninstall() {
drupal_uninstall_schema('themeless');
}
timeless.module
function themeless_process(&$variables, $hook) {
if ($hook == 'page') {
if (isset($variables['page']['content']['system_main']['nodes']) && is_array($variables['page']['content']['system_main']['nodes'])) {
$node = $variables['page']['content']['system_main']['nodes'];
$nodes = array_keys($node);
$result = db_query("SELECT t.nid AS themeless, n.promote
FROM {themeless_node} t, {node} n
WHERE t.nid=:nid
AND n.nid=t.nid",
array('nid' => $nodes[0]));
$tdata = $result->fetchObject();
if (isset($tdata->themeless) && $tdata->themeless > 0 && $tdata->promote != 1) {
if ($node[$nodes[0]]['body']['#object']->body['und'][0]['format'] == 'php_code') {
print $node[$nodes[0]]['body'][0]['#markup'];
} else {
print $node[$nodes[0]]['body']['#object']->body['und'][0]['value'];
}
exit();
}
}
}
}
function themeless_form_alter(&$form, &$form_state, $form_id) {
$parts = explode('_',$form_id);
$form_type = $parts[count($parts)-1].'_'.$parts[count($parts)-2];
$themeless = '';
if ($form_type == 'form_node') {
if (isset($form_state['node']->nid) && $form_state['node']->nid) {
$themeless = db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $form_state['node']->nid))->fetchField();
}
$checked = ($themeless == 1) ? 'checked' : '';
$form['themeless'] = array(
'#type' => 'fieldset',
'#title' => t('Themeless Node'),
'#weight' => 5,
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['themeless']['themeless_node'] = array(
'#type' => 'checkbox',
'#title' => 'Themeless Node',
'#description' => 'This theme will be displayed without any wrapper themes.',
'#weight' => 100,
'#default_value' => $themeless,
);
}
}
function themeless_node_insert($node) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
function themeless_node_update($node) {
if ($node->themeless_node == 1) {
if (db_query("SELECT COUNT(*) AS themeless
FROM {themeless_node}
WHERE nid=:nid",
array('nid' => $node->nid))->fetchField() != 1) {
$result = db_query("INSERT INTO {themeless_node} (nid)
VALUES( :nid )",array('nid' => $node->nid));
}
} else {
$result = db_query("DELETE FROM {themeless_node}
WHERE nid=:nid",array('nid' => $node->nid));
}
}
timeless.info
name = Themeless
description = Gives the option to a node to have a themeless display or displayed without the various theme templates native to Drupal.
core = 7.x
version = 7.x-1.0dev

Resources