Auto fill the MultiCheckbox on back-end - checkbox

I am creating an application on zend2 and I would like to get help.
I want to automatically fill some checkboxes in the backend.
The method getMessages() returns the following array:
array(
'info' => 'INFO',
'alert' => 'ALERT',
'more' => 'MORE'
);
Form creation
$msg = array(); // my array
foreach ($this->getMessages() as $key => $value) {
if(in_array($key, $user_values)) {
$msg[$key][1] = 'user';
}
if(in_array($key, $admin_values)){
$msg[$key][2] = 'admin';
}
if(!in_array($key, $user_values) && !in_array($key, $admin_values)){
$msg[$key][] = 'skip';
}
$form->get(trim($key))->setValueOptions(array($msg))->setChecked(true);
// OR
$form->get(trim($key))->setValue(array($msg))->setChecked(true);
// Clear the array
$msg = array();
}
The result I'd like to obtain:
<input type="checkbox" name="alert[]" value="skip' />
<input type="checkbox" name="alert[]" value="user' />
<input type="checkbox" name="alert[]" value="admin' />

You can use setValue() method to set the value that shoud be selected (or checked). You can also use setAttribute('selected', 'selected') eventually.

Related

Can't display file validation error message in codeigniter

I have set form validation in my project. My all form validation is working but I can not display file input validation error message. The file is upload properly, it doesn't show any error when I upload an invalid file. I try a lot of ways but anythings are not working.
I give here only file uploading related code.
My controller
$config = [
'upload_path'=>'./uploads/image/',
'allowed_types'=>'jpg|png',
'max_size' => '400',
'overwrite' => FALSE
];
$this->load->library('upload', $config);
if(!($this->form_validation->run() && $this->upload->do_upload()))
{
$view = array('error' => $this->upload->display_errors());
$view['admin_view'] = "admin/add_books";
$this->load->view('layouts/admin_layout', $view);
}
MY model
public function add_books()
{
$data = $this->upload->data();
$image_path = base_url("uploads/image/".$data['raw_name'].$data['file_ext']);
$data = array(
'book_name' => $this->input->post('book_name'),
'description' => $this->input->post('description'),
'author' => $this->input->post('author'),
'publisher' => $this->input->post('publisher'),
'price' => $this->input->post('price'),
'quantity' => $this->input->post('quantity'),
'categoryId' => $this->input->post('categoryId'),
'book_image' => $image_path,
'userId' => $this->session->userdata('id'),
'status' => $this->input->post('status')
);
$insert_book = $this->db->insert('books', $data);
return $insert_book;
}
My view
<div class="form-group row">
<label for="book_image" class="col-sm-2 col-form-label">Book image</label>
<div class="col-sm-6">
<?= form_upload(['name'=>'userfile', 'class'=>'form-control'])?>
<div class="text-secondary">* Upload PNG, JPG format. Image should not be more than 400KB</div>
</div>
<div class="col-sm-4">
<div class="text-danger form-error"><?= form_error('userfile')?></div>
</div>
</div>
How it can be fixed?
I think you should separate $this->form_validation->run() and $this->upload->do_upload()
$view = array();
if($this->form_validation->run() == true){
if(!$this->upload->do_upload('userfile')){
$view['error'] = $this->upload->display_errors();
}
}else{
$view['error'] = validation_errors();
}
if(array_key_exists('error', $view)){
$view['admin_view'] = "admin/add_books";
$this->load->view('layouts/admin_layout', $view);
}else{
//Insert the record
}

cakephp 3.0 passing data to the form.php

I am using a modelless form to send a contact email. I am using the example in the cookbook.
With the change to data in objects form arrays I am unsure what form the data is in being passed to the ContactForm.php
I have tried $data['name'] and $data[0]['name']
View for input name without the data[]
<input type="text" class="form-control" name="name" placeholder="Your Name" required="" aria-required="true" aria-invalid="false">
PagesController.php
public function contact(){
$this->request->allowMethod('ajax');
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
$data = array(
'status' => 'successful'
);
} else {
$data = array(
'status' => 'error'
);
}
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
}
}
ContactForm.php
protected function _execute(array $data)
{
// Send an email.
$email = new Email('default');
$email->emailFormat('html');
$email->template('demoTemplate')->viewVars( array('userName' => $data[0]['name'],
'userCompany' => '$data',
'userEmail' => '$data',
'userPhone' => '$data'));
$email->from('info#domain.com');
$email->to('$data');
$email->bcc('$data');
$email->subject('Contact Form Submission');
if ($email->send()) {
return true;
}
else {
return false;
}
}
Well for do this I use first this tool advanced-rest-client, and inside the code of cakephp you can use try and catch, you can user debug() too, example debug($data); in combination with advanced-rest-client you can see the result.
and if debug dont work serialice the data
$this->set('data', $data);
$this->set('_serialize', ['data']);
but even when serialized data use advanced-rest-client, just select the post option and type the url of where you want to get the post.
so:
public function contact(){
$this->request->allowMethod('ajax');
$contact = new ContactForm();
if ($this->request->is('post')) {
if ($contact->execute($this->request->data)) {
debug($this->request->data());//first
$datos = $this->request->data();//second
$data = [
'content' => $datos,
'status' => 'successful',
];
} else {
$datos = $this->request->data();
$data = [
'content' => $datos,
'status' => 'error,
];
}
$this->set(compact('data')); // Pass $data to the view
$this->set('_serialize', 'data');
}
}

WordPress WP_Query showing only first element in the array

I am currently learning on WordPress plugin development and I am trying to build a short code for my plugin
my plugin is basically a custom post type called property which have 3 meta data boxs in it
price location and date of construction
and one taxonomy called property type which be setted at the backend with rent or sale
all of this works and if you put them in wordpress they will work
But my shortcode file does work properly the loop on the WP_Query should return all the post which I have made but instead its returning only the first element found in the WP_Query
Can anyone guide me or fix where I have mistaken please
thanks all
now my short code file name is: properties_post_type_shortcode.php
My plugin file name is: properties_post_type.php
code for properties_post_type_shortcode.php
<?php
add_shortcode('land_properties',function(){
$loop = new WP_Query(
array(
'post_type' => 'property_post',
'orderby' => 'title'
)
);
if ($loop->have_posts()){
$output = '<ul class="land_properties_list">';
$i=0;
while( $loop->have_posts() ){
$loop->the_post();
$meta=get_post_meta(get_the_id(),'' );
$output= '
<li>
<a href="' .get_permalink() . '">
' . get_the_title() . ' | '.
$meta['property_price'][0]. " " .
$meta['property_location'][0]. " " .
$meta['property_date'][0]. " " .
'
</a>
<div>' . get_the_excerpt() . '</div>
</li>
';
}
}
else {
$output="No lands added";
}
// $loop->wp_reset_postdata();
return $output;
});
code for properties_post_type.php
<?php
/*
* Plugin Name: properties_post_type
* Plugin URI: Have not be set yet
* Description: this plugin allow you to create custom post type property which you can be modified and edited
* Version: 1.0
* Author: Muhab Alwan
* Author URI: https://www.facebook.com/HaaaB
* License: A "Slug" license name e.g. GPL2
*/
class PROP_POST_TYPE{
//default contructor
public function __construct()
{
$this->register_post_type();
$this->taxonomies();
$this->metaboxes();
}
public function register_post_type()
{
$args= array(
'labels' => array(
'name'=> 'Properties',
'singular_value' => 'Property',
'add_new' => 'Add New Property',
'add_new_item' => 'Add New Property',
'edit_items' => 'Edit_Items',
'new_item' => ' Add New Items',
'view_item'=> 'View Item',
'search_items' => 'Search Items',
'not_found' => 'No Property Found',
'not_found_in_trash' => 'No Property Found In Trash'),
'query_var' =>'properties',
'rewrite' => array(
'slug' => 'property/'),
'public' => true,
'menu_position' => 80, // set postion in the backend menu
'menu_icon' => admin_url(). 'images/media-button-other.gif', // define an image for the prop
'supports' => array(
'title',
//'editor',
'excerpt',
//'custom-fields' when we need user to build their own meta box Not required in project
) // specify what wordpress types are custom post type support
);
register_post_type('property_post', $args );
}
public function taxonomies()
{
$taxonomies = array();
$taxonomies['property_type'] = array(
'hierarchical' => true,
'query_var' => 'movie_genere',
'rewrite' => array('slug' => 'prop/type'
),
'labels' => array(
'name'=> 'Properties Type',
'singular_value' => 'Property Type',
'add_new' => 'Add New Property Type',
'add_new_item' => 'Add New Property Type',
'edit_items' => 'Edit Properties Type',
'new_item' => ' Add New Properties Type',
'view_item'=> 'View Property Type',
'search_items' => 'Search Properties Type',
'popular_items' => 'Popular Properties Type',
'separate_items_with_comments' => 'Separate Property Type With Comments',
'add_or_remove_items' => 'Add Or Remove Properties Type',
'choose_from_most_used' => 'Choose From Most Used Properties Type'
)
);
$this-> register_all_taxonomies($taxonomies); // register all taxonomies build in this plugin
}
public function register_all_taxonomies($taxonomies)
{
// foreach is for registering many taxonomy
foreach ($taxonomies as $name=> $arr)
{
//register ( what the taxonomies name, array of the object type that we register ex post or page
register_taxonomy($name,array('property_post'),$arr );
}
}
public function metaboxes()
{
// FIRST PRICE META BOX
add_action('add_meta_boxes', function(){
//css id, title, cb func, page, priority level, call back func argum
add_meta_box('property_price','Property Price', 'property_price','property_post');
add_meta_box('property_location','Property Location', 'property_location','property_post');
add_meta_box('property_date','Date Of Construction', 'property_date','property_post');
});
//PRICE PROP
function property_price($post){
$price_length = get_post_meta($post->ID,'property_price', true);
?>
<p>
<label for="property_price"> :</label>
<input type="number" pattern="[0-9]+" size="50" class="widfat" name="property_price" id="property_price" value="<?php echo esc_attr($price_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_price']))
{
update_post_meta(
$id,'property_price',
strip_tags($_POST['property_price'])
);
}
});
// LOCATIO PROP
function property_location($post){
$location_length = get_post_meta($post->ID,'property_location', true);
?>
<p>
<label for="property_location"> :</label>
<input type="text" class="widfat" name="property_location" id="property_location" value="<?php echo esc_attr($location_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_location']))
{
update_post_meta(
$id,'property_location',
strip_tags($_POST['property_location'])
);
}
});
function property_date($post){
$dof_length = get_post_meta($post->ID,'property_date', true);
?>
<p>
<label for="property_date"> :</label>
<input type="date" class="widfat" name="property_date" id="property_date" value="<?php echo esc_attr($dof_length)?>" /> </p>
<?php
}
add_action('save_post', function($id){
if ( isset ($_POST['property_date']))
{
update_post_meta(
$id,'property_date',
strip_tags($_POST['property_date'])
);
}
});
//third date of construction metaboxes
}
}
// initialization essential to build a cust post
add_action('init', function(){
new PROP_POST_TYPE();
include dirname(__FILE__). '/properties_post_type_shortcode.php';
});
To query all posts, add the following to the args of WP_Query:
'posts_per_page' => -1
Your code:
$loop = new WP_Query( array(
'post_type' => 'property_post',
'orderby' => 'title',
'posts_per_page' => -1
) );

Only last image uploaded from array when uploading multiple images in MYSQL with PHP

I'm trying to upload multiple images from a textbox to MYSQL database using PHP.
But somehow it only inserts the last item from the array in the database.
I tried uploading using one image, and that worked.
What am I doing wrong?
form.php:
<form action="addpicture.php?id=<?php echo $prodID; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="image[]" multiple/>
<input type="submit" value="upload" name="image" class="btn btn-primary" />
</form>
Addpicture.php:
<?php
session_start();
include '../includes/config.php';
$prodID = $_GET['id'];
foreach(array_keys($_FILES['image']['error']) as $key){
$temp_name = $_FILES['image']['tmp_name'][$key];
$t_name = file_get_contents($temp_name);
$t_name = mysql_real_escape_string($t_name);
$insert = mysql_query("INSERT INTO tblpictures(prodID, foto) VALUES ('$prodID','$t_name')") or die(mysql_error());
header('location: form.php?prodID=' . $prodID);
exit();
}
?>
EDIT: SOLVED
HTML 5 multi file upload with PHP
You're using the PHP array-based naming for file uploads. PHP's treatment of that in the $_FILES array is BEYOND moronic.
Single files show up as
$_FILES = array(
'fieldname' => array('error' => ..., 'name' => '...', etc....)
);
As soon as you go into array mode, you get a completely DIFFERENT structure:
$_FILES = array(
'fieldname' => array (
'error' => array(
0 => 'error code of first file'
1 => 'error code of second file'
etc...
)
'name' => array(
0 => 'first filename',
1 => 'second filename',
etc...
)
)
)
You need to loop on:
foreach(array_keys($_FILES['image']['error']) as $key) {
$name = $_FILES['image']['name'][$key];
$temp_name = $_FILES['image']['tmp_name'][$key];
}

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.

Resources