How to populate the select options from a table in phalcon? - php

I have a list containing tags with id name and status in a table and in my Model TagsStandard I have this:
const STATUS_APPROVED = 1;
const STATUS_DISABLED= 0;
public $id;
public $name;
public $status;
public static function getAllTag()
{
$tags = TagsStandard::find(array(
"status = 'STATUS_APPROVED'",
"order" => "id"
));
}
So with this I am getting all the tags. Now at Controller in indexAction I have:
$tags = TagsStandard::getAllTag();
if ($tags) {
$this->view->tags = $tags;
$this->view->name = array("name" => $tags->name->toArray());
}
And in the index I have:
<select id='user-skills-input' class="select-chosen" type="text" data-role="tagsinput" value="" multiple>
<?php if(count($tags) > 0): ?>
<?php foreach($tags->items as $idx => $tag):
echo "<option value='" . $tag->id . "'> " . $tag->name . "</option>" ?>
<?php endforeach; ?>
<?php endif; ?>
</select>
The values are not showing up in the options and so can anyone help me with this?

<?php
echo \Phalcon\Tag::select(array(
"user-skills-input",
TagsStandard::find(array(
"status = 'STATUS_APPROVED'",
"order" => "id"
)),
"using" => array("id", "name")
);
Phalcon Tags#select

Related

Two mysql query searches on same page?

So I have two MySql searches on my jQuery mobile page but they do not work together.
Here is the code:
my index.php code:
<?php
require "functions.php";
$posts = getAllPosts();
$posts = getSearchPosts();
?>
<?php
for( $p = 0; $p < count( $posts ); $p++ )
{
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php echo $posts[$p]["search_role"];?> <!-- using getSearchPosts -->
<?php echo $posts[$p]["search_genre"];?>
<?php echo $posts[$p]["user_first_name"];?> <!-- using getAllPosts -->
<?php echo $posts[$p]["user_last_name"];}?>
</div>
</div>
Functions.php:
function getSearchPosts()
{
require "config.php";
$posts = $c->query ( "SELECT * FROM posts" );
if ( $posts->num_rows > 0 )
{
while( $row = $posts2->fetch_assoc() )
{
$postData[] = array( "user_id" => $row[ "user_id" ], "search_role" => $row[ "search_role" ], "search_genre" => $row[ "search_genre" ] );
}
} else {
return "No Data";
}
return $postData;
}
function getAllPosts()
{
require "config.php";
$posts = $c->query ( "SELECT * FROM users" );
if ( $posts->num_rows > 0 )
{
while( $row = $posts->fetch_assoc() )
{
$postData[] = array( "user_id" => $row[ "user_id" ], "user_first_name" => $row[ "user_first_name" ], "user_last_name" => $row[ "user_last_name" ] );
}
} else {
return "No Data";
}
return $postData;
}
I assume I am to change the $posts on one function to something else such as $posts -> $search or something but it does not echo anything after changing. What can I do to have both searches done at the same time?
Do them as two separate loops. It makes no sense to show them both in the same DIVs, since there's no correspondence between the results of the two queries.
$posts = getSearchPosts();
foreach ($posts as $post) {
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php
echo $post['search_role'];
echo $post['search_genre'];
?>
</div>
</div>
<?php
}
$users = getAllPosts();
foreach ($users as $user) {
?>
<div class="ui-corner-all custom-corners">
<div id="searchpost">
<?php
echo $user['user_first_name'];
echo $post['user_last_name'];
?>
</div>
</div>
<?php
}

Dependent dropdown for country and state in yii 1.13

I had created two database tables as,
Country
State
In Country table i had countryid & cname field. In State table i had state_id, state_name & country_cid.
Now i need to make a dependent dropdown i.e. when i select country dropdown box, then the particular state for that country should be displayed. I had done below coding. But it displays only country and not displays state.
This is in views/sample/register.php file.
<div class="row">
<?php echo $form->labelEx($model,'countryid');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('SampleController/dynamicSubcategory'),
array('coountry_id'=>'js:this.value'),
'dataType' => 'JSON',
'success'=>'js:function(data)'
. '{'
. 'var html="<option value=>-----Select city-----</option>";'
. '$.each(data,function(i,obj)'
. '{'
. 'html+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. '});'
. '$("#state_id").html(html);'
. '}'
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_id','', array());
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$countryId=$_POST['coountry_id'];
$criteria=new CDbCriteria();
$criteria->select=array('state_id,state_name');
$criteria->condition='country_cid='.$countryId;
$criteria->order='state_name';
$cityAry= State::model()->findAll($criteria);
$ary=array();
foreach($cityAry as $i=>$obj)
{
$ary[$i]['state_id']=$obj->id;
$ary[$i]['state_name']=$obj->name;
}
echo json_encode($ary);
}
I had created Country model & State model. I had analyzed many sites. But i can't get right. Please anybody help.
You can try below code which I have used in one of my projects -
**Code in the view file :**
<?php $arrOptionsCountry = array('prompt'=>'Select Country','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site','SearchValueStates'),'update'=>'#Airports_state','beforeSend'=>'stateLoading'));
echo $form->dropDownList($model,'country',$arrCountryList,$arrOptionsCountry,array('class'=>'span11 customDropdown1_select'));
$arrOptionsState = array('prompt'=>'Select State','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site', 'SearchValueCities'),'update'=>'#station_name','beforeSend'=>'cityLoading'));
echo $form->dropDownList($model,'state',$arrStatesList,$arrOptionsState);
echo $form->dropDownList($model,'city',$arrCityList);
?>
**Site Controller :**
public function actionSearchValueStates()
{
$arrParam =array();
if(isset($_POST['Airports']['country']))
{
$Term = $_POST['Airports']['country'] ;
$case = "STATE-LIST";
$prompt = "Select State";
$arrParam['id'] = isset($Term)?$Term:null ;
$data = States::getList($case,$arrParam);
$data = CHtml::listData($data,'id','name');
echo CHtml::tag('option',array('value'=>''),$prompt,true);
foreach($data as $value=>$name)
{
echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
}
}
Yii::app()->end();
}
I got the answer for my question.
This is in views/sample/register.php file
<div class="row">
<?php echo $form->labelEx($model,'country');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/dynamicSubcategory'),
'update'=>'#state_name',
'data'=>array('country_id'=>'js:this.value'),
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_name','', array(), array(
'prompt'=>'Select State'
));
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$data=State::model()->findAll('country_cid=:countryid',
array(':countryid'=>(int) $_POST['country_id']));
$data=CHtml::listData($data,'state_id','state_name');
echo "<option value=''>Select State</option>";
foreach($data as $value=>$state_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($state_name),true);
}
This code works fine for dependent dropdown in yii

Codeigniter - How to create a form with undefined number of input?

So I've been trying to create an 'add' function for a contest table that is also linked to a joining table as the contest has many sport events associated to it (and a sport events will also be included in many contests). I have managed to create it as below, however it is limited to only adding one row into the joining table based on the chosen game in a dropdown.
So now, how do I go about creating the form if I don't know how many sport events there might be? How will the website create another dropdown if one dropdown is used so that more sport events can be selected? Similarly, how does the controller know that there are x amount of dropdowns selected, and hence x amount of rows to be added to the joining table?
I'm sorry if I am using incorrect or ambiguous terms to describe my problem. I have only started learning and creating websites recently.
Thank you.
UPDATE: I may have a solution per the updated codes below. However I am now stuck on the inserting into the database page. For some reason when I click submit, the next page loads but with no error and no rows inserted. Please help :)
View
<h1>Add New Contest</h1>
<?php
echo form_open('contests/add/');
?>
<?php
echo "<br />" "<br />"
echo "Contest Name";
$data = array( 'name' => 'contest_name',
'value' => set_value('contest_name'),
);
echo form_input($data);
echo "<br />" "<br />"
echo "Game";
?>
<div class="field_wrapper">
<div>
<select name="field_name[]">
<option value="" disabled selected>Select Game</option>
<?php
foreach($events_lists->result() as $row) {
$sports_events_id = $row->sports_events_id;
$sports_events_start_date = $row->sports_events_start_date;
$sports_events_start_time = $row->sports_events_start_time;
$home_team_shorthand = $row->home_team_shorthand;
$away_team_shorthand = $row->away_team_shorthand;
?>
<option value="<?php echo $sports_events_id; ?>"><?php echo $home_team_shorthand; ?> v <?php echo $away_team_shorthand; ?> - <?php echo $sports_events_start_date; ?> <?php echo $sports_events_start_time; ?></option>
<?php } ?>
</select>
<img src="add-icon.png"/>
</div>
</div>
<?php
echo "<br />" "<br />"
$data = array( 'value' => 'Add Contest',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
Controller
function add()
{
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
foreach ($data['leagues_list']->result() as $row) {
$league_insert_id = $row->id;
$this->load->module('sports_events');
$data['events_lists'] = $this->sports_events->get_events_list($league_insert_id);
}
if ($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add_contest';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data1 = array(
'contest_name' => $this->input->post('contest_name')
);
if(isset($_REQUEST['submit'])) {
$data2 = $_REQUEST['field_name'];
}
if ($this->_transactions_new_contest($data1, $data2)) {
return $query;
$this->session->set_flashdata('team_phase_created', 'The team phase has been set');
redirect('/contests/');
}
}
}
Model
function _transactions_new_contest($data1, $data2){
$this->db->trans_start();
$this->db->insert('contests', $data1);
$contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
foreach ($contest_id->result() as $row) {
$contest_result_id = $row->id;
foreach($data2 as $value){
$this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $value . ')');
} }
$this->db->trans_complete();
}

Codeigniter getting multiple data in foreach in controller

I have a problem regarding my foreach loop wherein i cannot access the first array or the array[0] and i dont know the problem.
here is the controller:
$this->SessionCheck();
$this->user->initialize($this->session->userdata('userid'));
$this->load->model('project_model', 'Project');
$ProjectID = $this->input->post('ProjectID');
/***************** Intialize Project model ******************/
$this->Project->Initialize($ProjectID);
$Options = Work_breakdown_structure::$WithBaseTaskID;
//$PhaseTaskID = (int)$this->input->get_post('TaskID',TRUE);
$PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->PhaseTaskID = $this->Project->getPhaseBaseTaskID($ProjectID);
$postlist->phaseList = $this->Project->LatestApplicablePlan->WBS->GetPhaseList($Options);
if($PhaseTaskID == null)
{ }
else
{
foreach($PhaseTaskID as $index=>$value)
{
$finalArr[$value['TaskName']] = $value['BasetaskID'];
$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($finalArr[$value['TaskName']], $Options);
}
echo print_r($finalArr);
for($x = 1 ; $x < 2 ; $x++)
{
//$postlist->taskList = $this->Project->LatestApplicablePlan->WBS->GetWBS($phaseID, $Options);
}
}
$postlist->project = $ProjectID;
return $this->load->view('MyToDoPhaseDropdown', $postlist);
here is my view:
echo '<td style="padding-top:5x;font-size:14px;" colspan="2"> <br> Phases : ';
echo '<select id="phases_select" style="width:400px;" onchange="search_filter()" >';
echo '<option value="0" selected="selected"> Select Project Phase </option>';
foreach($phaseList as $row)
{
if(preg_match("/^CYCLE/", strtoupper($row['TaskName'])))
{
foreach($row['Child'] as $child)
{
echo '<option value="'. $child['TaskID']. '">';
echo $row['TaskName'].' > '.$child['TaskName'] . '</option>';
}
}
else
{
if($Iterate['BaseTaskID'] != $row['TaskID'])
{
echo '<option value="'. $row['TaskID']. '">';
echo $row['TaskName'].'</option>';
}
foreach($taskList as $Iterate)
{
if($row['TaskID'] == $Iterate['BaseTaskID'] )
{
echo '<option value="'. $row['TaskID']. '">';
echo $Iterate['TaskName'].' '.$Iterate['IterationNumber']. '</option>';
}
}
}
}
echo '</select>';
echo '</td>';
The problem is that i need to get all the values into an array to pass it to the view. but i only get the latest value which is the 2nd data that i retrieve in the database.
What you are doing wrong is :
return $this->load->view('MyToDoPhaseDropdown', $postlist);
You need to set the data in a variable to be accessible in view : http://codeigniter.com/user_guide/general/views.html
$data = array('title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message');
$this->load->view('MyToDoPhaseDropdown', $data);
And in view file : MyToDoPhaseDropdown.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>

Get data from DB to set as default in dropdown HTML/CSS/MYSQL/PHP

Hello guys I want to get data from the DB to set as default/selected in my dropdown.
I have a page named Update Project, in that page I have a dropdown component that is filled by records from my data, however I want to set the selected value from the query result.
This is what I've tried so far:
$st_ac = $conn->prepare( "SELECT p.project_code, m.type
FROM tblprojects as p
JOIN tblprojectsmaster as m
ON p.project_code = m.project_code
WHERE p.project_code = :code" );
$st_ac->execute(array(':code' => $code));
$result = $st_ac->fetch(PDO::FETCH_ASSOC);
$ptype = $result['type']; // the data to be selected in the dropdwon
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value"' . $type . '"';
if($ptype == $type)
echo 'selected="selected"';
echo '>' . $description . '</option>';
echo '<br />';
?>
<option value="<?php echo $type; ?>"><?php echo $description; ?></option>
<?php
}
?>
But I can't be able to achieve what I want. Any ideas? Your help will be truly appreciated. Thanks.
Try this
<select name="projectType">
<?php
for($i=0; $row_pt = $st_pt->fetch(); $i++){
$type = $row_pt['type'];
$description = $row_pt['description'];
echo '<option value="'.$type.'"';
if($ptype == $type)
{
echo 'selected="selected"';
}
echo '>'.$description.'</option>';
}
?>
May be you can use like this
echo '<option value="' . $type . '"'; if($ptype == $type) { echo 'selected="selected" } >'; echo $description . '</option>'; echo '<br />';

Categories