In my document archive system, have an edit view that should allow a user to edit certain data about the file they uploaded and even re-upload a file if need be. For some reason the edit view is not opening because it is says the variable am stating in the form is undefined.
I have tried changing the form details but nothing is working.
This is the edit.blade.php
<h3 class="box-title"><i class="fa fa-edit"></i> Edit Document</h3>
</div><!-- /.box-header -->
<div class="box-body">
{!! Form::open(['action' => ['DocumentsController#update', $doc->id],
'method' => 'PUT', 'enctype' => 'multipart/form-data']) !!}
{{ csrf_field() }}
<div class="form-group">
<label for="student_id">Student ID</label>
<select class="form-control" name="student_id">
#foreach($students as $student)
<option value="{{ $student->$id }}">{{ $student->$id }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="category_id">Category</label>
<select class="form-control" name="category_id">
#foreach($categories as $category)
<option value="{{ $category->$id }}">{{ $category->name }}
</option>
#endforeach
</select>
</div>
This is the update funtion in the documents controller
public function update(Request $request, $id)
{
$this->validate($request, [
'file' => 'nullable|max:1999|unique:documents',
'category_id' => 'nullable|integer',
]);
$doc = Document::findOrFail($id);
$doc->category_id = $request->input('category_id');
//$doc->file = $path;
$doc->mimetype = Storage::mimeType($path);
$size = Storage::size($path);
if ($size >= 1000000) {
$doc->filesize = round($size/1000000) . 'MB';
}elseif ($size >= 1000) {
$doc->filesize = round($size/1000) . 'KB';
}else {
$doc->filesize = $size;
}
// determine whether it expires
if ($request->input('isExpire') == true) {
$doc->isExpire = false;
$doc->expires_at = null;
}else {
$doc->isExpire = true;
$doc->expires_at = $request->input('expires_at');
}
if($request->hasFile('file'))
{
// filename with extension
$fileNameWithExt = $request->file('file')
>getClientOriginalName();
// filename
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
// extension
$extension = $request->file('file')-
>getClientOriginalExtension();
// filename to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
// upload file
$path = $request->file('file')->storeAs('public/uploaded
files/'.$user_id, $fileNameToStore);
Storage::delete('public/uploaded files/'. $doc->file);
$doc->file = $path;
}
$doc->save();
return redirect('documents')->with('flash_message','Successfully
Updated!');
Edit function in Controller
public function edit($id)
{
$doc = Document::findOrFail($id);
$categories = Category::all();
$cate = array();
foreach($categories as $category)
{
$cate[$category->id] = $category->name;
}
return view('documents.edit')->withDocuments($doc)->withCategories($cate);
//compact('doc','categories'));
}
this is the error
Undefined variable: doc (View:
C:\xampp\htdocs\unzadms\resources\views\documents\edit.blade.php)
I expect to be able edit the necessary file details.
Seens like $doc is undefined as it says, you should make sure you are using the $doc variable on the edit.blade.php file, especific on the controler that handles the display.
You should post that controller if you still need help.
Update: Take a look on the documentation:
https://laravel.com/docs/5.4/views#passing-data-to-views
Solution:
return view('documents.edit', ['doc' => $doc,'categories' => $cate]);
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'm using Laravel 5. I wanted to list all the database names in
dropdown, but I always end up fetching the last value. I already use
foreach loop, still nothing happens. Here's my code:
public function create(Request $request)
{
//echo "<pre>";
$sqlconn = mysqli_connect('127.0.0.1', 'root', '1234');
$showdb = "SHOW DATABASES";
$dbconn = mysqli_query($sqlconn, $showdb);
$dbnames = array();
while ($row=mysqli_fetch_assoc($dbconn)) {
$dbnames = $row;
foreach ($dbnames as $dbname => $value) {
if ($value != "information_schema" && $value != "performance_schema" && $value != "test" && $value != "mysql") {
//$dblists = implode(":", array($value));
$dblists = $value;
//print_r($dblists);
}
}
}
//die();
}
And here's my html codes:
<div class="col-md-12">
<div class="form-group #if($errors->has('description')) has-error #endif">
<div class="col-xs-2">
<label for="reports_description" class="control-label"><h5><b>Select Database:</b></h5></label>
</div>
<div class="col-xs-5">
<select class="form-control">
<option>---SELECT---</option>
<option value="{{$dblists}}">{{$dblists}}</option>
</select>
</div>
</div>
</div>
Controller:
public function create(Request $request) {
$databases = \DB::select('show databases');
return view('view.name', compact('databases'));
}
View:
#foreach($databases as $database)
<p>{{ $database->Database }}<p>
#endforeach
How can i upload csv file and save data in to my mysql database.
according to id.in cakephp 3
i am unable to do that. can any one help me.
my controller
public function import() {
if(isset($_POST["submit"])){
if($_FILES['file']['csv']){
$filename = explode('.', $_FILES['file']['csv']);
debug($filename);
if($filename[1]=='csv'){
$handle = fopen($_FILES['file']['csv'], "r");
while ($data = fgetcsv($handle)){
$item1 = $data[0];
// $item2 = $data[1];
// $item3 = $data[2];
// $item4 = $data[3];
$Applicants = $this->Applicants->patchEntity($Applicants, $item1);
$this->Applicants->save($Applicants);
}
fclose($handle);
}
}
}
$this->render(FALSE);
}
my view:
<div class="col-md-8">
<?= $this->Form->create('Applicants',['type' => 'file','url' => ['controller'=>'Applicants','action' => 'import'],'class'=>'form-inline','role'=>'form',]) ?>
<div class="form-group">
<label class="sr-only" for="csv"> CSV </label>
<?php echo $this->Form->input('csv', ['type'=>'file','class' => 'form-control', 'label' => false, 'placeholder' => 'csv upload',]); ?>
</div>
<button type="submit" class="btn btn-default"> Upload </button>
<?= $this->Form->end() ?>
</div>
Your question is a bit unclear what do you want to do in the controller do you want to update the existing records or save new data. If you want to update then only you need to use patchEntity.
The patchEntity should have a database entity fetched where in you can change or update the data as per your need, so in case if your first column contains the id of the Applications table then below code can work and in $data you can write whatever fields you want to update or add
So you can use the below code block instead
public function import() {
if(isset($_POST["submit"])){
if($_FILES['file']['csv']){
$filename = explode('.', $_FILES['file']['csv']);
debug($filename);
if($filename[1]=='csv'){
$handle = fopen($_FILES['file']['csv'], "r");
while ($data = fgetcsv($handle)){
$item1 = $data[0];
$data = array(
'fieldName' => $item1
);
// $item2 = $data[1];
// $item3 = $data[2];
// $item4 = $data[3];
$Applicant = $this->Applicants->newEntity($data);
$this->Applicants->save($Applicant);
}
fclose($handle);
}
}
}
$this->render(FALSE);
}
If you have more specific code/requirement then please share, so that I can help you out accordingly.
Here is my Solution to upload csv file and save database
public function import($id = NULL) {
$data = $this->request->data['csv'];
$file = $data['tmp_name'];
$handle = fopen($file, "r");
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row[0] == 'id') {
continue;
}
$Applicants = $this->Applicants->get($row[0]);
$columns = [
'written_mark' => $row[1],
'written_comments' => $row[2],
'viva_mark' => $row[3],
'viva_comments' => $row[4]
];
$Applicant = $this->Applicants->patchEntity($Applicants, $columns);
$this->Applicants->save($Applicant);
}
fclose($handle);
$this->set('title','Upload Student CSV File Input Number and others');
return $this->redirect($this->referer());
}
I want to style the field and its dropdown of jQuery autocomplete, but the way around is only through the controller I suppose because there, I'm able to concat the variables I need and send it to the jQuery autocomplete on the Blade file. But concatenating only echoes out the variables as a field, I wish to style the output like it is on the image attached to this post. How do I achieve this?
This is the controller:
public function SelectLocationPlaces(Request $userAdressRequest)
{
$term = $userAdressRequest->term;
$data = LocationPlaces::where('name', 'LIKE', '%'.$term.'%')->take(10)->get();
$countries = Country::all();
$countryFlag = CountryFlag::all();
$results = array();
foreach ($data as $key => $value) {
foreach ($countries as $key => $values) {
if($value->country_id === $values->iso_alpha2){
$countrySelected = $values->name;
$selectedCapital = $values->capital;
}
}
foreach ($countryFlag as $key => $valueFlag) {
if($countrySelected === $valueFlag->name){
$countryPerFlag = $valueFlag->flag;
$countryCurrency = $valueFlag->currency;
}
}
$results[] =
**
['value'=>$value->name .$value->timezone_id .$countrySelected, ];
**
}
return Response::json($results);
}
This is the Blade file:
<DIV align="center"><SPAN class="div-header">USER ADDRESS</SPAN></DIV>
<div>{!! Form::text('city_town', Input::old('city_town'), ['class'=>'css-classes', 'placeholder'=>'area/city', 'id'=>'city_town']) !!}</div>
<div>{!! Form::text('state_province_region', Input::old('state_province_region'), ['class'=>'css-classes', 'placeholder'=>'state/province', 'id'=>'state_province_region']) !!}</div>
<script type="text/javascript">
$('#city_town').autocomplete({
source: '{{ url('json/redirects') }}',
minLength: 1,
autofocus: true,
select: function(e, ui){
$('#state_province_region').val(ui.item.state_province_region);
$('#name').val(ui.item.name);
}
});
</script>
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......