I have one little problem with checkboxes in yii. I have modal popup, where i have form for update.
Here is my controller:
public function actionUpdateroomrow(){
$model = Rooms::findOne($_POST['id']);
$model -> room_number_of_people = $_POST['room_number_of_people'];
$model -> room_name = $_POST['room_name'];
if(isset($_POST['room_air_conditioning']))
$model -> room_air_conditioning = $_POST['room_air_conditioning'];
else $model -> room_air_conditioning = false;
$model->update();
if (isset ($_POST['room_multimedia_id'])){
foreach($_POST['room_multimedia_id'] as $key => $value){
$model2 = RoomMultimediaData::findOne($value);
$model2 -> room_multimedia_data_value = $key;
var_dump($model2 -> errors);
}
}
$this->redirect('index');
}
Where is problem? In this row.
<div class="form-group">
<?php foreach($room_multimedia as $rm){ ?>
<label><?= $rm->room_multimedia_title ?></label><input type="checkbox" name="room_multimedia_id[<?= $rm->Checkmultimediadata($room->room_id,$rm->room_multimedia_id)->room_multimedia_data_id ?>]" value="<?= $rm->room_multimedia_id ?>"/>
<?php } ?>
</div>
This is row from update formular and im not really sure, where i failed.
In RoomMultimedia.php, modul i have this:
public function Checkmultimediadata($room_id,$room_multimedia){
return RoomMultimediaData::find()->where('room_id='.$room_id.' and room_multimedia_id='.$room_multimedia.'')->one();
}
Warning from yii:
PHP Warning – yii\base\ErrorException
Creating default object from empty value
$model2 -> room_multimedia_data_value = $key;
Can you help me solve this?
Thank you all! :)
Related
I have a generic update query in a file, I know it is being called by the my projectscontroller but I do not know whether the issue is between the form and controller, form and function or function and controller.
My code is supposed to work where from the Project list form is populated with records with edit and delete buttons (this works),when the EDIT button is chosen the Editproject form will populate with the data in that line (this works). After editing the info displayed in the form the user presses save which calls the EDIT function in the project controller which in turn calls the save function then the update function and thus updates the database (this doesnt work). I am not sure where the error is as no error is occuring and i know the code is entering the EDIT function of the controller because after it does it opens the list again.
I am sure the error is some stupid typo i made somewhere, and if your wondering the save function can go to update or insert functions but the insert works perfectly fine.
This is why I'm 80% sure it has something to do with the update function itself or the way im passing the info to the update function.
Any help would be greatly appreciated, my project table create is at the end and like I said, I'm sure its as simple as a typo somewhere I am overlooking (it always is with me).
Update function (and save)
private function update($fields) {
$query = ' UPDATE `' . $this->table .'` SET ';
foreach ($fields as $key => $value) {
$query .= '`' . $key . '` = :' . $key . ',';
}
$query = rtrim($query, ',');
$query .= ' WHERE `' . $this->primaryKey . '` = :primaryKey';
//Set the :primaryKey variable
$fields['primaryKey'] = $fields['id'];
$fields = $this->processDates($fields);
$this->query($query, $fields);
}
public function save($record) {
try {
if ($record[$this->primaryKey] == '') {
$record[$this->primaryKey] = null;
}
$this->insert($record);
}
catch (PDOException $e) {
$this->update($record);
}
}
Project Controller
<?php
class ProjectController {
private $employeesTable;
private $projectsTable;
public function __construct(DatabaseTable $projectsTable, DatabaseTable $employeesTable) {
$this->projectsTable = $projectsTable;
$this->employeesTable = $employeesTable;
}
public function list() {
$result = $this->projectsTable->findAll();
$projects = array();
foreach ($result as $project) {
$projects[] = [
'IDP' => $project['IDP'],
'ProjectID' => $project['ProjectID'],
'ProjectName' => $project['ProjectName'],
'ProjectDes' => $project['ProjectDes'],
'ProjectStartDate' => $project['ProjectStartDate'],
'ProjectEndDate' => $project['ProjectEndDate'],
'ProjectStatus' => $project['ProjectStatus']
];
}
$title = 'Project list';
$totalProjects = $this->projectsTable->total();
return ['template' => 'projects.html.php',
'title' => $title,
'variables' => [
'totalProjects' => $totalProjects,
'projects' => $projects
]
];
}
public function home() {
$title = 'Colpitts Design';
return ['template' => 'home.html.php', 'title' => $title];
}
public function delete() {
$this->projectsTable->delete($_POST['id']);
header('location: index.php?action=list');
}
public function edit() {
if (isset($_POST['project'])) {
$project = $_POST['project'];
$project['projectstartdate'] = new DateTime();
$project['projectenddate'] = null;
$this->projectsTable->save($project);
header('location: index.php?action=list');
} else {
if (isset($_GET['id'])) {
$projects = $this->projectsTable->findById($_GET['id']);
}
$title = 'Edit Projects';
return ['template' => 'editproject.html.php',
'title' => $title,
'variables' => [
'project' => $projects ?? null
]
];
}
}
}
editproject form
<form action="" method="post">
<input type="hidden" name="project[IDP]" value="<?=$project['IDP'] ?? ''?>">
<label for="ProjectID">Type the Project id here:</label>
<textarea id="ProjectID" name="project[ProjectID]" rows="3" cols="40"><?=$project['ProjectID'] ?? ''?></textarea>
<label for="ProjectStatus">Type the Project status here:</label>
<textarea id="ProjectStatus" name="project[ProjectStatus]" rows="3" cols="40"><?=$project['ProjectStatus'] ?? ''?></textarea>
<label for="ProjectName">Type the Project name here:</label>
<textarea id="ProjectName" name="project[ProjectName]" rows="3" cols="40"><?=$project['ProjectName'] ?? ''?></textarea>
<label for="ProjectDes">Type the Project description here:</label>
<textarea id="ProjectDes" name="project[ProjectDes]" rows="3" cols="40"><?=$project['ProjectDes'] ?? ''?></textarea>
<input type="submit" name="submit" value="Save">
projectlist form
<p><?=$totalProjects?> projects are listed in the DanClock Database.</p>
<?php foreach($projects as $project): ?>
<blockquote>
<p>
<?=htmlspecialchars($project['ProjectID'], ENT_QUOTES, 'UTF-8')?>
<?=htmlspecialchars($project['ProjectDes'], ENT_QUOTES, 'UTF-8')?>
<?=htmlspecialchars($project['ProjectStartDate'], ENT_QUOTES, 'UTF-8')?>
<?=htmlspecialchars($project['ProjectStatus'], ENT_QUOTES, 'UTF-8')?>
Edit
<form action="index.php?action=delete" method="post">
<input type="hidden" name="id" value="<?=$project['IDP']?>">
<input type="submit" value="Delete">
</form>
</p>
</blockquote>
<?php endforeach; ?>
Projects table
CREATE TABLE `Projects` (
`IDP` int(11) NOT NULL AUTO_INCREMENT,
`ProjectID` int(11) NOT NULL,
`ProjectName` varchar(50) NOT NULL,
`ProjectDes` text,
`ProjectStartDate` Datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ProjectEndDate` Datetime,
`ProjectStatus` varchar(50) NOT NULL DEFAULT 'Active',
PRIMARY KEY (IDP)
) ENGINE=InnoDB;
I figured out the issue, as i thought it was my update function. It wasnt as "generic" as I thought it was, or it was almost.
this line:
//Set the :primaryKey variable
$fields['primaryKey'] = $fields['id'];
should be:
//Set the :primaryKey variable
$fields['primaryKey'] = $fields[$this->primaryKey];
Somethhing small that I didnt notice, now to continue on with everything else ><
I am creating an event, each event will have attendees, I got this working fine, the problem I am having is an attendee can attend the same event twice, which is not good.
Event View
<?php if($this->session->userdata('user_id')): ?>
<hr>
<?php echo form_open('/attendees/add/'.$event['id']); ?>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['user_id']; ?>">
<input type="submit" value="I'm in!" class="btn btn-success">
</form>
<?php endif; ?>
Attendees Controller
<?php
class Attendees extends CI_Controller {
public function add($event_id) {
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('user_id', 'required|callback_check_userid_eventid');
if($this->form_validation->run() === FALSE){
$this->session->set_flashdata('attendee_not_added', 'You are already on the list.');
redirect('home');
} else {
$this->attendee_model->add_attendee($event_id);
// Set message
$this->session->set_flashdata('attendee_added', 'You have been added to this event.');
redirect('events');
}
}
}
Attendees Model
<?php
class Attendee_model extends CI_Model {
public function __contruct() {
}
public function get_attendees($id = FALSE){
if($id === FALSE) {
$query = $this->db->get('attendees');
return $query->result_array();
}
$this->db->select('attendees.id, attendees.team, attendees.is_goalie, event.id, user.first_name, user.last_name');
$this->db->from('attendees');
$this->db->join('event', 'attendees.event_id = event.id', 'inner');
$this->db->join('user', 'attendees.user_id = user.id', 'inner');
$this->db->where('event.id', $id);
$query = $this->db->get();
return $query->row_array();
}
public function add_attendee($event_id){
$data = array(
'event_id' => $event_id,
'user_id' => $this->session->userdata('user_id')
);
return $this->db->insert('attendees', $data);
}
// Check attendee exists in event
public function check_userid_eventid($event_id, $user_id){
$query = $this->db->get_where('attendees', array('user_id' => $user_id, 'event_id' => $event_id));
if(empty($query->row_array())){
return true;
} else {
return false;
}
}
}
As you can see I tried creating a custom callback on the button form validation but it did not work.
If anyone can point me in the right direction, let me know if I am even somewhat close.
Thanks in advance.
You are not passing the $event_id value to the callback function. Replace your validation with the following line
$this->form_validation->set_rules('user_id', 'User ID', 'required|callback_check_userid_eventid['.$event_id.']');
add following callback function inside the Attendees Controller file
public function check_userid_eventid($user_id, $event_id){
$CI =& get_instance();
$CI->load->database();
$CI->form_validation->set_message('user_id_unique', "Sorry, that %s is already being used.");
return isset($CI->db) ? ($CI->db->limit(1)->get_where('attendees',compact('user_id','event_id'))->num_rows() == 0) : false;
}
Your callback is in a model that form validation knows nothing about. If you look at the docs: callbacks should be in the same controller as the form validation method that uses it.
However, you can use a function in a model as a callback with a different syntax:
$this->form_validation->set_rules(
'username', 'Username',
array(
'required',
array($this->users_model, 'valid_username')
)
);
as documented here.
Finally, on a false return, you need to make sure that you are setting a message as seen in this example:
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
In conclusion: the documentation has all the answers.
Put the call back function into Controller
<?php
class Attendees extends CI_Controller {
public function add($event_id) {
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('user_id', 'required|callback_check_userid_eventid');
if($this->form_validation->run() === FALSE){
$this->session->set_flashdata('attendee_not_added', 'You are already on the list.');
redirect('home');
} else {
$this->attendee_model->add_attendee($event_id);
// Set message
$this->session->set_flashdata('attendee_added', 'You have been added to this event.');
redirect('events');
}
}
// Check attendee exists in event
public function check_userid_eventid($event_id, $user_id){
$query = $this->db->get_where('attendees', array('user_id' => $user_id, 'event_id' => $event_id));
if(empty($query->row_array())){
return true;
} else {
return false;
}
}
}
I used a drop down button to select an option from the given options. But when I selected an option it does not display that in the box. And I it gives chance only once to select an option. For the drop down I retrieve data from the database.
This is the view code (Its inside Assign_Inquiries)
<select id = "counsellorname" name="counsellornamename" class="btn btn-default dropdown-toggle">
<option value = "0"> Select Category Name</option>
<?php
foreach($result as $row){
echo "<option value = ".$row['email'].">".$row['fname']." ".$row['lname']."</option>";
}
?>
</select>
Its really great if someone can help me. Thanks inadvance
This is the controller code
<?php
class Assign_Inquiries_Controller extends CI_Controller{
function index(){
$this->load->model('Assign_Inquiries_Model');
$data['result'] = $this->Assign_Inquiries_Model->index();
//print_r($data);
$this->load->view('Assign_Inquiries',$data);
}
}
?>
This is the model code
<?php
class Assign_Inquiries_Model extends CI_Model{
function index(){
$this->db->select('first_name,last_name,email');
$where = "status =3";
$this->db->where($where);
$query = $this->db->get('user');
foreach ($query -> result() as $row) {
$data[] = array(
'fname' => $row->first_name,
'lname' => $row->last_name,
'email' => $row->email
);
}
return $data;
}
}
?>
Change your model code as below: use result_array() which returns the result in array format.
function index(){
$this->db->select('first_name,last_name,email');
$this->db->where('status',3);
$query = $this->db->get('user');
return $query ->result_array();
}
In view you loop must be like this....
foreach($result as $row){
echo "<option value = ".$row['email'].">".$row['first_name']." ".$row['last_name']."</option>";
}
where am i going wrong in my extraction of country name from mysql database? (codeigniter: activerecord enabled)
Its printing out "default country" instead of expected "Australia".
Pages Controller
public function view($page)
{
$page = strtoupper($page); // Capitalize the first letter
$data = array(
'title' => 'My Title',
'country' => 'default country'
);
$this->getCountryName($page, $data);
if(!is_null($data['country'])){
$page = "country";
}
$this->load->helper('url');
$this->load->helper('utility');
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
if(!is_null($data['country'])){
$this->load->view('templates/infobox', $data);
}
$this->load->view('templates/footer', $data);
}
function getCountryName(&$page, &$data){
$this->db->select('name')->from('pv_country')->where('code', $page);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data['country'] = $row;
echo $row;
}
}
}
Country View
<div style =" position:absolute;top:90%; background: red;">
<?php echo $country; ?></div> // prints default country.
</div>
A PHP Error was encountered
Severity: 4096
Message: Object of class stdClass could not be converted to string
Filename: pages/country.php
Line Number: 25
so i put in some more debugging and found the correct syntax/method to call to get the result,
which then returns an object with attributes that need to be accessed in the view.
function getCountryName(&$page, &$data){
$this->db->select('name')->from('pv_country')->where('code', $page);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['country'] = $query->row();
}
}
<?php echo $country->name; ?>
I use CodeIgniter 2.1.3, PHP and MySQL.
Hello, I want to display data from database. Always I display by foreach($results as $data), but now I want do display all data in few step. Display first record and when user click next then display next row from database. I now that I must use mysql_fetch_row() but I don't know how I can do it...
This is my model:
public function play($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("quiz");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
controler:
public function index()
{
$config = array();
$config["base_url"] = base_url() . "index.php/main_menu/Quiz/index";
$config["total_rows"] = $this->quiz_model->record_count();
$config["per_page"] = 11;
$config["uri_segment"] = 4;
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data["results"] = $this->quiz_model->play($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view('left_column/quiz_open', $data);
}
Pagination is not important.
and view:
<form>
<?php
if (empty($results)) {
}
else {
foreach($results as $data) { ?>
<label style='width:450px;'> <b>   <?php echo $data->pytanie?> </b> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp1 ?> /> <?php echo $data->odp1 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp2 ?> /> <?php echo $data->odp2 ?> </label>
<label style='width:300px;'> <input type="radio" name="Wiek" value=<?php echo $data->odp3 ?> /> <?php echo $data->odp3 ?> </label>
<?php }
}?>
<label style='width:300px;'> <input type="submit" name="Wyslij" id="Wyslij" value="  Wyślij  "/> </label>
</form>
There is an inbuilt Pagination class provided by codeIgniter. You can find it in user guide.
Define a start index variable in the function where u want to use pagination as zero.
public function pagination($start_index = 0)
{
$result = $this->model->get_results($data); //this $data is the argument which you are passing to your model function. If you are using database to get results array.
$items_per_page = 10; //this is constant variable which you need to define
$filtered_result = array_splice($result, $start_index, ITEM_PER_PAGE_USERS);
$model['$filtered_result'] = $filtered_result;
$total_rows = count($result);
$model['page_links'] = create_page_links (base_url()."/controlelr_name/pagination",ITEM_PER_PAGE_USERS, $total_rows);
$this->load->view('controller_name/view_file_name', $model);
}
This is a generalised function for pagination. You can keep this function in one helper file where you keep all generalised functions.
function create_page_links($base_url, $per_page, $total_rows)
{
$CI = & get_instance();
$CI->load->library('pagination');
$config['base_url'] = $base_url;
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;
$CI->pagination->initialize($config);
return $CI->pagination->create_links();
}
This create page links function is a generic function.............for more explanation check pagination class from user guide......