CakePHP 2, CakePHP conditions, Dynamic condition on search, MySQL expression - php

I am trying to build a search query for report in my CakePHP application. In my query condition building go through a if, else statements. On initial load of report I want to load the pre-defined criteria and when user submit the search conditions will be changed on selection.
This is my initial conditions
$conditions['Report.expense_status'] = array('COMPLETED');
$conditions['DATE(Report.created) >='] = "date_sub(now(), interval 2 month)";
When user do a search conditions should update as below.
if ($this->request->is('post')) {
$search = $this->request->data('Report');
if( strlen($search['From']) > 0 ){
$conditions['DATE(Report.created) >='] = date( 'Y-m-d',strtotime($search['From']) );
}
}
But my initial condition code output the SQL expression as below and it is not getting populate the result.
DATE(`Report`.`created`) >= 'date_sub(now(), interval 2 month)'
it is adding quotes to the expression.
How should prevent adding quotes around condition?
Form:
<?php echo $this->Form->create('Report', array('action' => 'index')); ?>
<div>
<?php
echo $this->Form->input('Keyword');
echo $this->Form->input('Status',
array(
'options' => $status,
'multiple'=> 'false'
)
);
echo $this->Form->input('Child',
array(
'options' => $children,
'multiple'=> 'false'
)
);
echo $this->Form->input('From',
array(
'id' => 'report_from'
)
);
echo $this->Form->input('To',
array(
'id' => 'report_to'
)
);
?>
<div class="footer">
<div>
<input type="submit" value="Search" name="action">
<input type="button" value="Cancel" name="action">
</div>
</div>
</div>
<?php echo $this->Form->end(); ?>

Related

Cakephp 3 Search Function

got a question about cakephp3 search function, is it possible to search among two tables/Controllers in a search form?
this is the codes, am trying to search from categories name and also products name, their relationship is products has category id
this is the code from the Controller
$c = $this->request->getQuery('c');
if(!empty($c)) {
$this->loadModel('Categories');
$category = TableRegistry::get('Categories');
$query = $this->Products->find()->contain(['Categories'=>['Products']])
->where(['Categories.name LIKE' => '%' . $c. '%']);
}
$this->set(compact('c','query'));
$key = $this->request->getQuery('key');
if(!empty($key)) {
$products->where(['Products.name LIKE ' => '%'.$key.'%']);
}
$this->set(compact('key'));
this is from the HTML side, where i name="c", it only search for c and not key,
<?php echo $this->Form->create(null, ['type' => 'get', 'valueSources' =>
'query'); ?>
<?php echo $this->Form->control('search', ['type' => 'hidden']); ?>
<input type="text" class="form-control" name="c" placeholder="Search...">
<span class="input-group-append">
<button type="submit">
<?php echo $this->Form->end(); ?>
is there a method to combine both search in a form?
thank you for your helps

Advice for voting form with php and bitrix

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>
?>

update mysql datatable using checkbox in loop form

i'm trying to update a custom table for my wordpress plugin, first im getting the roles from my table then display it using a form and this works fine, now the problem is that when i check the boxs it update in database, but when i uncheck it, it dont update at all and if i uncheck it all i get this error message
Warning: Invalid argument supplied for foreach() in C:\wamp\www\wp_test\wp-content\plugins\Data\settings.php on line 52
<?php
$roles=get_editable_roles();
global $wpdb;
$table_name = $wpdb->prefix. "Author_detailed_repport";
?>
<h3>Settings Page</h3>
<h4>Add/Remove a role from filter list</h4>
<p>This setting allow you to add/remove roles from the filter<br />
list, here down a list of all the roles existing in your website, all<br />
you have to do is to check/uncheck wich you wanna add/rmove from filter list</p>
<form action="<?php $_REQUEST['PHP_SELF'] ?>" method="post">
<?php
require_once('../wp-config.php');
$i=0;
foreach($roles as $role)
{
$rom=$role['name'];
$results = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" );
if ($results==NULL)
{$wpdb->insert( $table_name, array(
'role' => $role['name'],
'statut' => '',
'post_number' => '',
'activate' => ''
));
}?>
<input type="checkbox" name="cat[]" value="<?php echo $i+1 ;?>" <?php checked($results[0]->statut, $i+1); ?> />
<input type="hidden" name="ww" value="0">
<?php
?>
<label>
<?php echo $results[0]->role;?></label><br />
<?php $i++; } ?>
<input type="submit" value="save" name="saveme" />
</form>
<?php
if(isset($_POST['saveme']))
{
$cats=$_POST['cat'];
foreach($cats as $cam)
{
if(isset($cam))
{
$wpdb->update( $table_name, array(
'statut' => $cam
),array('ADR_id' => $cam),array('%d'));}
else
{
$wpdb->update( $table_name, array(
'statut' => '0'
),array('ADR_id' => $cam),array('%d'));
}
}
}
?>
Because $roles is not set yet and there you need to do a another check
If(isset($roles)) {
//foreach loop goes in here
}

Calling PHP function from HTML form on same page

So I have looked around online and found some questions on here about it, but nothing seemed to work for my situation.
I have a form which should call a function that is set on the page.
The form's html is as follows:
<form method="post" action="">
<textarea id="input-box" placeholder="What's on your mind?" maxlength="10000" name="quick-post-area" class="col-md-offset-2 col-md-6"></textarea>
<input type="submit" value="Post" class="col-md-2" id="quick-post-submit">
</form>
and the function:
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$author_id = 1;
$slug = 'post';
global $current_user;
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$pollq_question = wp_kses_post( trim( $_POST['pollq_question'] ) );
$post_id = wp_insert_post(
array(
'comment_status' => 'open',
'ping_status' => 'closed',
'post_author' => $current_user->ID,
'post_name' => $slug,
'post_title' => 'Posted By:' . $current_user->ID,
'post_status' => 'publish',
'post_type' => 'post',
'post_content' => $_POST['quick-post-area']
)
);
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
} // end programmatically_create_post
and finally the isset that I am trying to use to call the function:
if(isset($_POST['submit']))
{
quick_post();
}
Anyone got any ideas about what I need to change for it to fire?
This line is searching for an object with the name submit on it
if(isset($_POST['submit']))
{
But your form doesn't have such object, so add a name to your input and the function shall work:
<input type="submit" name="submit" value="Post" class="col-md-2" id="quick-post-submit">
<input type="submit" value="Post" class="col-md-2" id="quick-post-submit">
vs
if(isset($_POST['submit']))
{
quick_post();
}
you didn't give the submit button a name="submit" attribute

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