Advice for voting form with php and bitrix - php

Currently working with Bitrix CMS and need to make vote for users from specific group. With knowing id of group i made a form with bunch of radio buttons inside. When someone vote, result shoud be writen in file (or database) and page with "Thank you for voting!" should be displayed.
My question is what is the best way to do it?
I tried a few different ways:
1) this tutorial, not working
2) two another web tutorials, can link if you ask me
3) Voting form from bitrix, but for that module of the system should be change, and that not advised.
Below is page with vote itself, but "poll.php" makes me confused because of not knowing right way to do it. So good advice would be really appreciated.
p.s. you can ignore 'Bitrix' part, most important is php
/*get users from group in array*/
<?$arUsers = CGroup::GetGroupUser(20);
$iCountUsers = 0;
$arUsersbyGroupID = array();
foreach($arUsers as $arUser) {
$arUserbyID = CUser::GetByID($arUser);
$rsUserbyID = $arUserbyID -> Fetch();
$arUsersbyGroupID[] = $rsUserbyID; }
$iCountUsers++;?>
<div class="wrapper">
<div id="poll-container">
<form class="grid" action="poll.php" method="post" accept-charset="utf-8">
/*for each create element with radio button*/
<?$iVoteCount = 0;
$allopt = array();
foreach($arUsersbyGroupID as $Vote) {
$photo = $Vote["PERSONAL_PHOTO"];
if (!empty($photo)) {
$name = "{$Vote["NAME"]} {$Vote["LAST_NAME"]}";?>
<div class="cell">
<div class="cell_img"><?echo CFile::ShowImage($photo)?></div>
<div class="cell_caption">
<input type="radio" value="<?=$iVoteCount?>" name="vote" onclick="getVote(this.value)" />
<label for='opt<?=$iVoteCount?>'><?echo $name?></label>
</div>
</div>
$iVoteCount++;
}
} ?>
<div id="sub"><input type="submit" value="Vote" /></div>
</form>
</div>
</div>

You shouldn't write your fully custom solution for creating polls. In Bitrix Framework we have a module called - vote
With supply of this module you can create standard polls or if they are not fit to your tasks - you can customize them, but you should not be writing all these code from scratch.
For basic polls configuration you can read official online courses (in Russian) - http://dev.1c-bitrix.ru/learning/course/index.php?COURSE_ID=41&LESSON_ID=2859

Use bitrix api to transfer your array data using $_POST or $_REQUEST global varibles binding them to your custom form name[] . Just add bitrix api code on after submit event. Voting results may be pasted into the custom lead fields that should be previously created in BX manually. Check out this example. It was fully workable and tested.
<?php
$queryUrl ='';
$_SERVER['REMOTE_ADDR'] = $ip;
$queryData = http_build_query($basebitrix24 = array(
'fields' => array(
"TITLE" =>'one',
"NAME" => 'two',
"LAST_NAME" => $leadData['question_one'],
"STATUS_ID" => "NEW",
"OPENED" => "Y",
"UF_CRM_1491235024" => $leadData['question_second'],
"UF_CRM_1491235124" => $leadDataQ1[$answer],
"UF_CRM_1491235376" => $leadData['question_third'],
"ASSIGNED_BY_ID" => 16,
'SOURCE_ID' => $i,
"PHONE" => array(array("VALUE" => $_REQUEST['phone'], "VALUE_TYPE" => "WORK" )),
"EMAIL" => array(array("VALUE" => $_REQUEST['email'], "VALUE_TYPE" => "WORK" )),
),
'params' => array("REGISTER_SONET_EVENT" => "Y")
));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $queryUrl,
CURLOPT_POSTFIELDS => $queryData,
));
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result, 1);
?>
The requests are not about voting but there is no very much trouble to use same method for any custom form too. Form code in example purposes.
if (isset($_POST['s_submit'])) {
#$email = strtolower(trim($_POST['email']));
#$name = trim($_POST['name']);
if (isset($_POST) && count($_POST) != 0) {
if (#isset($email) && #$email != '') {
$line = check_record_exist($removelist, $email, $form_type);
if ($line) {
$line--;
delete_line_from_file($removelist, $line);
}
if (!check_record_exist($addlist, $email, $form_type)) {
add_record($addlist, $email, $name);
$sm_res = 1;
} else {
$sm_res = 3;
}
} else
echo '<font color="#FF0000">Please enter e-mail address</font>';
}
}
if (isset($sm_res)) {
switch ($sm_res) {
case '1': echo '<b>You have successfully subscribed</b>';
break;
case '2': echo '<b>You have successfully unsubscribed</b>';
break;
case '3': echo '<b>You are already subscribed</b>';
break;
case '4': echo '<b>You are already unsubscribed</b>';
break;
}
unset($sm_res);
} else {
<form name="contactform" id="sky-form" method="post" action="">
<fieldset>
<div class="row">
<div class="sky-form epochta">
<section class="col col-6" >
<label class="input"><i class="icon-append icon-envelope-alt"></i> <h3>EMAIL </h3><input type="email" name="email" value="<?$_REQUEST['email']?>"> </label>
</section>
<?php if ($form_type != 1) { ?>
<section class="col col-6">
<label class="input"> <i class="icon-append icon-user"></i><h3>NAME<h3> <input type="text" name="name" size="15" value="<?php echo #trim(strip_tags($_REQUEST['name'])); ?>">
</label>
</section>
<?php } ?>
<section class="col col-12" >
<input type="hidden" name="saved" value="yes">
<input type="submit" class="subbutton" name="submit" value="">
<td align="center" colspan="2"><font face="Verdana" size="-2">ePochta Subscription Manager</font>
</section>
</div>
</div>
</fieldset>
</form>
?>

Related

How to submit Form data from PHP via mamp to Google spreadsheet

I am struggling to find out why it's able to send some data but not others. It submits 'email' and 'password' and 'id'... and just doesn't post 'sex' and 'dob'... I've been staring at it for the past several days.
function doPost(e){ //this doPost(e) function on my app script app is able to allow interaction between my php and my app script app
var error = null;
if(typeof e.parameter.action == 'undefined'){
error = "action parameter required";
}
else if(e.parameter.action == "CRUD"){ //CREATE RECORD PROCCESS - the updateRecord() function is able to create record on a row with corresponding email.
var result = updateRecord(e.parameter.email.trim(), e.parameter.password.trim(), e.parameter.id.trim(), e.parameter.sex.trim(), e.parameter.date.trim(), e.parameter.dob.trim());
}
following is the function which is called by doPost(e) on my app script, and then proceeds to do Update or Create new record if an email does not exist... by basically appending to the spreadsheet.
function updateRecord(email, password, id, sex, date, dob) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = sheet.getSheetByName("profiledata");
var lastRow = mySheet.getLastRow();
var ar = [email,password,id,sex,date,dob];
var newRecord = [email,password,id,sex,date,dob];
var range = mySheet.getRange(2, 1, lastRow - 1);
var check = range.createTextFinder(email).findNext(); // this line of code checks the row and gets data by email
var status;
if (check) {
check.offset(0, 0, 1, ar.length).setValues([ar]);
// status = 'Record Updated';
return {
status: "success",
message: "Record Updated"
}
}
else {
range.offset(lastRow - 1, 0, 1, ar.length).setValues([newRecord]);
// status = 'New Record created';
return {
status: "success",
message: "New Record created"
}
}
}
Following is my PHP insert file... post.php... which is able to send form data toward the above doPost(e) function, which in turn runs updateRecord() function
$url = "App script URL "; //this is where I pasted the URL of my app script
$postData = [
"action" => "CRUD",
"email" => $_POST['email'],
"password" => $_POST['password'],
"id" => $_POST['id'], // "ignore this Comment!!" I create an id separately and echo it into the html form input as readonly.
"sex" => $_POST['sex'],
"date" => $_POST['date'],
"dob" => $_POST['dob'],
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postData
]);
$result = curl_exec($ch);
$result = json_decode($result, 1);
if($result['status'] == "success"){
$returnmsg = $result['message'];
$_SESSION['success'] = $returnmsg;
header("location: table.php?=success $returnmsg");
}else{
$_SESSION['error'] = $result['message'];
$errormsg = $result['message'];
header("location: table.php?=err$errormsg");
}
Below is my HTML form
<form method="post" action="post.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" name="email" class="form-control" placeholder="Enter email" autocomplete="on">
</div>
<div class="form-group">
<label for="password">password Field</label>
<input type="password" name="password" class="form-control" placeholder="this is a place for password" autocomplete="on">
</div>
<div class="form-group">
<label for="id">id Field</label>
<input type="text" name="id" class="form-control" value="<?php echo $id;?>" readonly>
</div>
<div class="form-group">
<label for="sex"> Gender Field</label>
<input type="text" name="sex" class="form-control" placeholder="this is a place for gender" autocomplete="on">
</div>
<div class="form-group">
<label for="dob">Date of Birth Field</label>
<input type="text" name="dob" class="form-control" placeholder="this is a place for DOB" autocomplete="on">
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
my problem is that this process is only able to send data to the spreadsheet but only up to 'id'... it doesn't submit 'sex' and 'date'
I searched all over google's documentation, and other places, I am coming up with nothing...

Unable to preserve input values after form validation Codeigniter 4

This is a question I have seen asked before but I have been unable to find an answer for the newer version of Codeigniter.
Controller
<?php
namespace App\Controllers;
class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = \Config\Services::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = \Config\Services::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = \Config\Services::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = \Config\Services::email();
// Set email settings
$emailC->setFrom('bensirpent07#benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman#gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
};
*/
}
}
}
Contact View
<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
From my understanding of the way validation used to work in CodeIgniter, is that when you loaded your view after a form validation it would update the values with what was previously entered. This does not seem to be the case for CodeIgniter 4. I've also tried directly loading the views rather than calling the index function on validation fail. Still would not fill in the form values.
Now I could just pass these values to the index function via $data array. Which is the fix I'm going to use for now. This is more so a sanity check to see if there is something basic I'm missing or if I'm incorrectly using the validation format for CodeIgniter 4.
in CI4 you can use old() function to preserve the input value upon form validation:
View file:
<input type="tel" name="phone" value="<?= old('phone'); ?>">
In Controller you must use withInput() in the redirect() code:
$validation = \Config\Services::validation();
$request = \Config\Services::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}

Code Igniter form submit returns empty page

I had this code dumped on me. I know nothing about Code Ignitor and a little about php. I have a form that returns a selected value. However, when I click on the submit button, it returns back to the right page but with no code on it at all. I cannot figure out where the problem is. The claim does not seem to be going into the database by setting the user id so I don't think it's getting that far. What can I try?
The form:
<form method="post" action="/sp/makeClaim">
<div class="text-center" style="padding-bottom: 20px;">
<select name="spId">
<option value="-1"<?php $this->printSelected($spId, -1);?>>-- Choose a Service Provider --</option>
<?php
foreach ($spData as $id => $name)
{
?>
<option value="<?php echo $id; ?>"<?php $this->printSelected($spId, $id);?>><?php print($name); ?></option>
<?php
}
?>
</select>
</div>
<div class="text-center">
<input type="submit" class="btn btn-default sp" value="Make Claim from List Above" /><br />
or<br />
Add Your Service Provider Information
</div>
</form>
The controller code:
public function makeClaim()
{
$formDefaults = array(
'spId' => -1
);
if ($this->input->post())
{
foreach ($formDefaults as $key => $defaultValue)
{
$$key = trim($this->input->post($key));
if ($spId == -1)
{
$this->addError('You must choose the service provider you wish to claim.');
}
}
$sp = $this->getEm()->getRepository('Entities\ServiceProvider')->findOneBy(array('id' => $spId));
if (is_null($sp))
{
$this->addError('A service provider with that ID could not be found.');
}
if (count($this->getErrors()) == 0)
{
$claim = new \Entities\Claim();
$claim->setUser($this->getUser());
$claim->setSP($sp);
$claim->setStatus('New');
$claim->setLastUpdated(new DateTime(date('Y-m-d H:i:s')));
$claim->setLastUpdatedBy($this->getUser()->getRealName() . ' (' . $this->getUser()->getId() . ')');
$this->em->persist($claim);
$this->em->flush();
$this->_redirect(true, 'Your claim on that service provider account has been submitted for review. We will contact you with a status update after we review your request.', '/sp/makeClaim/');
}

PHP form only returning empty array

I am working on a code segment that is a messaging function next to a list of names. On the page there is an envelope and when you click it a pop-up window appears with a text area inside of it. I would like to be able to fill that textarea with characters and send it as a message using my already functioning sendMessage function. I know my sendMessage function works and I've isolated the issue to the return given by the submit button. How do I get my submit button to POST the textarea to the page (keep in mind there are 2+ forms on this page). The code looks like this:
if (empty($_POST) === false) {
print_r($_POST);
$blah = $_POST;
echo "<script>window.top.location='asd.$blah'</script>";
}
if (empty($_POST['Send']) === false) {
echo "<script>window.top.location='../hidden/PNMasdd.php?gpa=$var1&year=$var2&major=$var3&sport=$var4'</script>";
echo 'YOU ARE IN THE SENDING MESSAGE FIELD';
if( empty ($_POST['message_full']))
{
$errors[] = 'All fields must be filled in!';
//print_r($errors);
}
if(empty($_POST) === false && empty($errors) === true)
{
$receiver_id = $temp_user['id'];
$sender_id = $user_data['id'];
$type = 0;
if(empty($is_Convo))
{
$is_Convo = 0;
}
$blahVar = $user_data['id'] . ',';
$message = str_replace("\r\n", "<br>", $_POST['message_full']);
$message_data = array(
'sender_id' => $user_data['id'],
'receiver_id' => $receiver_id,
'message_full' => $message,
'is_opened' => $blahVar,
'isConvo' => $is_Convo,
'type' => $type
);
//Put data limit code here
send_message($message_data);
$my_exten = "Messages/messages.php";
$noti_data = array(
'id_receive' => $receiver_id,
'id_sent' => $user_data['id'],
'type' => 1,
'exten' => $my_exten
);
notify($noti_data);
echo '<center>';
echo '<div class="alert alert-info">
<strong>It sent!</strong> You have sent a message successfully!
</div>
';
echo '</center>';
}
else{
echo output_errors($errors);
}
}
?>
<form id="wow" name="wow" action="" method="POST">
<div class="row">
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<center>
<textarea maxlength="100000" data-msg-required="Please enter your message." rows="10" cols="100%" class="form-control" name="message_full" id="message_full"></textarea>
</center>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<table width=90%><td width=45%><button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button></td><td width=45%>
<button type="submit" value="Send Message" name="Send" onclick="document.getElementById('wow').submit()" class="btn btn-primary">Send</button>
As pointed out in the comments, the buttons need to be inside your form.
Your setup is a bit odd for my taste, but try this out.. it will mostlikely need some tweaks and i'm not sure about the cancel button..
<form id="wow" name="wow" action="" method="post" >
<div class="form-group required">
<div class="col-md-12">
<textarea name="message_full" id="message_full" rows="10" cols="100%" class="form-control" maxlength="10000" placeholder="Please enter your message." autocomplete="off"></textarea>
</div>
</div>
<div class="buttons"> <!-- add css for this or change the class to yours.. -->
<input class="btn btn-default" data-dismiss="modal" value="Cancel" />
<input class="btn btn-primary" type="submit" value="Send Message" />
</div>
</form>
As #Barmar just said, you don't have any field named 'Send'. You should change:
if (empty($_POST['Send']) === false)
to:
if (empty($_POST['message_full']) === false)
(Edit)
Only the fields inside your form will get to $_POST superglobal, the submit button will not get there

Render Radio Element in Zend Forms

I have defined a form using Zend\Form. In that, there is a radio button.
$this->add(array(
'name' => 'nationality_radio',
'type' => 'Radio',
'options' => array(
'value_options' => array(
'local' => 'Local',
'expatriate' => 'Expatriate',
),
)
));
Its value is not directly binded with database column. But it should populate correct value taken form DB and save user input back. (eg - if value of table column nationality is local it should select local in radio button)
When rendered it should display as..
On form load, it will a select option considering column nationality. It will contain value either local or expatriate
<?php
if ($candidate->nationality == 'local'){
$local = 'checked';
} else if ($candidate->nationality == 'local'){
$expatriate = 'checked';
}
?>
In plain HTML i can do it as below,
<div class="profile_item list-group-item">
<span class="item_title">Local: </span>
<span class="item_content"><input type="radio" name="nationality" value="local" <?php echo $local ?>></span><br>
<span class="item_title">Expatriate: </span>
<span class="item_content"><input type="radio" name="nationality" value="expatriate" <?php echo $expatriate ?>></span>
</div>
But since Zend form rendered using <?php echo $this->formRow($form->get('nationality_radio')); ?> I couldn't do it. It just displayed as below.
How can i achieve my requirement ?
For set the value, within controller method:
$form = new YourFormClass();
//are you using fieldsets? let's say no...
//if accepted value for $candidate->nationality could be only 'local' and 'expatriate',
//check the scope with your defined value_options or use an if
$form->get('nationality_radio')->setValue($candidate->nationality);
On your view use formRadio helper:
<?php echo $this->formRadio($form->get('nationality_radio'),\Zend\Form\View\Helper\FormRadio::LABEL_PREPEND);?>
Check out documentation at: http://framework.zend.com/manual/2.2/en/modules/zend.form.elements.html#radio
or check classes:
\Zend\Form\View\Helper\FormRadio
and
\Zend\Form\View\Helper\FormMultiCheckbox
Accepted values for $labelPosition are:
const LABEL_APPEND = 'append';
const LABEL_PREPEND = 'prepend';
Try this
<?php
if ($candidate->nationality == 'local'){
$LocalChecked="checked";
}
else {
$expatriateChecked ="checked";
}
?>
<div class="profile_item list-group-item">
<span class="item_title">Local: </span>
<span class="item_content"><input type="radio" name="nationality" value="local" <?php echo $LocalChecked ?>></span><br>
<span class="item_title">Expatriate: </span>
<span class="item_content"><input type="radio" name="nationality" value="expatriate" <?php echo $expatriateChecked ?>></span>
</div>

Categories