Codeigniter data from view to controller - php

Each User has multi profiles. once they logged in, they are asked to select a profile,
here is the code for Form to select profile.
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 align ="center" class="panel-title">Select Profiles</h3>
</div>
<div class="panel-body">
<?php
foreach($resJacs->{'details'} as $key) {
echo form_open('selectaccess', array(
'class' => 'form-group',
'role' => 'form'
));
echo form_submit(array(
'value' => $key->profile_name,
'name' => $key->profile_type,
'class' => 'btn btn-lg btn-default btn-block'
));
echo form_close();
}
?>
</div>
</div>
</div>
</div>
when user selects the profile profile id is passed to session for later use. here is the code for "selectaccess",
public function SelectAccess() {
$sess_data = array(
'id' => $this->session->userdata['is_logged_in']['id'],
'prfid' => $this->input->post('')
);
print_r($sess_data);
}
how can i prfid as mentioned in selectaccess method.

I just want to give an example, maybe this can help u :
I am use pure html .
<form action="SelectAccess/<?php echo $id; ?>">
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
Controller
function SelectAccess($val='') {
$input = $this->input->post('name');
$_SESSION['whatever'] = $val;
}

Normally you need to know the name of the field in order to get the value at the controller. But you are dynamically creating the field names so that gets tricky.
Fortunately you are only posting one input so $_POST should have only one item. The way your view is written the value of $_POST[0] will be provided by $key->profile_name. Hopefully, that value is what you are looking for.
public function SelectAccess() {
{
$sess_data = array(
'id' => $this->session->userdata['is_logged_in']['id'],
'prfid' => isset($_POST[0])) ? $_POST[0] : NULL;
);
}

Related

CodeIgniter 4 - Cannot submit data with TinyMCE text editor but with normal text area data gets submitted

I am trying to integrate TinyMCE editor with CodeIgniter 4 application. However the data from the tinyMCE textarea is not getting submitted to database even when i click on submit button but with normal textarea the data is submitted to database easily.
Also when i edit & update the submitted data, it gets updated in the database but the text formatting from tinyMCE is erased and data is saved as normal text in the database.
Here is my code below
Add page controller
public function addPage() {
if(!session()->has('logged_staff')) {
return redirect()->to(base_url(). "/team");
}
$data = [];
$data['validation'] = null;
$suid = session()->get('logged_staff');
$data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
$data['memrole'] = $this->adminModel->getMemberRole($suid);
$data['permission'] = $this->adminModel->getPermission($suid);
$checkPermission = $this->adminModel->checkPermission($suid);
$memrank = $this->adminModel->getMemberRank($suid);
if(is_array($memrank)) {
if($memrank['rank'] == 'Super Admin') {
}
elseif(isset($checkPermission)) {
if($checkPermission['pages'] == 'Not Allowed') {
return redirect()->back();
}
}
}
if($this->request->getMethod() == 'post') {
$rules = [
'p_name' => [
'rules' => 'required|min_length[3]|max_length[250]',
'errors' => [
'required' => 'You cannot leave this field empty',
'min_length' => 'Title is short',
'max_length' => 'Title is too long',
]
],
'p_description' => [
'rules' => 'required',
'errors' => [
'required' => 'You cannot leave this field empty',
]
],
];
if($this->validate($rules)) {
$addContent = [
'p_name' => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING)),
'p_date' => date("Y-m-d h:i:s"),
'p_slug' => strtolower(url_title($this->request->getVar('p_name'))),
];
if($this->pageModel->insertContent($addContent)) {
$this->session->setTempdata('success', 'Page updated successfully', 3);
return redirect()->to(base_url()."/admin/pages");
} else {
$this->session->setTempdata('error', 'Oops! could not update the page', 3);
return redirect()->to(current_url());
}
} else {
$data['validation'] = $this->validator;
}
}
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/addpage", $data);
echo view("team/Templates/footer_panel");
}
Edit Page Controller
public function editPage($id=null) {
if(!session()->has('logged_staff')) {
return redirect()->to(base_url(). "/team");
}
$data = [];
$data['validation'] = null;
$suid = session()->get('logged_staff');
$data['staffdata'] = $this->adminModel->getLoggedStaffData($suid);
$data['memrole'] = $this->adminModel->getMemberRole($suid);
$data['permission'] = $this->adminModel->getPermission($suid);
$checkPermission = $this->adminModel->checkPermission($suid);
$memrank = $this->adminModel->getMemberRank($suid);
if(is_array($memrank)) {
if($memrank['rank'] == 'Super Admin') {
}
elseif(isset($checkPermission)) {
if($checkPermission['pages'] == 'Not Allowed') {
return redirect()->back();
}
}
}
$data['p_data'] = $this->db->table('tblpages')
->select('*')
->where(["id" => $id])
->get()
->getRow();
if($this->request->getMethod() == 'post') {
$rules = [
'p_name' => [
'rules' => 'required|min_length[3]|max_length[250]',
'errors' => [
'required' => 'You cannot leave this field empty',
'min_length' => 'Title is short',
'max_length' => 'Title is too long',
]
],
'p_description' => [
'rules' => 'required',
'errors' => [
'required' => 'You cannot leave this field empty',
]
],
];
if($this->validate($rules)) {
$pageContent = [
'p_name' => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING)),
'p_slug' => strtolower(url_title($this->request->getVar('p_name'))),
];
if($this->pageModel->updateContent($pageContent, $id)) {
$this->session->setTempdata('success', 'Page updated successfully', 3);
return redirect()->to(base_url()."/admin/pages");
} else {
$this->session->setTempdata('error', 'Oops! could not update the page', 3);
return redirect()->to(current_url());
}
} else {
$data['validation'] = $this->validator;
}
}
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/editpage", $data);
echo view("team/Templates/footer_panel");
}
Edit - Create Page View File
<?php
$page_session = \Config\Services::session();
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Add New Page</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item">Page List</li>
<li class="breadcrumb-item active">Add New Page</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="contact__form__title">
<?php if($page_session->getTempdata('success', 3)) : ?>
<div class="alert alert-success">
<?= $page_session->getTempdata('success', 3); ?>
</div>
<?php endif; ?>
<?php if($page_session->getTempdata('error', 3)) : ?>
<div class="alert alert-danger">
<?= $page_session->getTempdata('error', 3); ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</section>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card card-primary">
<ul class="nav nav-tabs nav-pills nav-fill">
<li class="nav-item">
Add Page
</li>
</ul>
<div class="card-body">
<div class="tab-content">
<div id="details" class="tab-pane active">
<?= form_open('admin/addPage/'); ?>
<div class="form-group row">
<div class="col-sm-12">
<?= csrf_field(); ?>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<label for="pTitle">Edit Title</label>
<input type="text" name="p_name" value="<?= set_value('p_name'); ?>" class="form-control" id="pTitle" placeholder="Page Name or Page Title" required>
<span class="text-danger"><?= display_errors($validation, 'p_name'); ?></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<label for="pContent">Edit Page Content</label>
<textarea id="editor" name="p_description" class="form-control" id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>
<span class="text-danger"><?= display_errors($validation, 'p_description'); ?></span>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary">Create Page</button>
Cancel
</div>
</div>
<?= form_close(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
init.js file - TinyMCE code to initiate the editor
tinymce.init({
selector: '#editor',
valid_elements : '*[*]',
});
Edited the addPage controller code - Still doesn't work
if(!$this->validate([
'p_name' => 'required|min_length[3]|max_length[250]',
'p_description' => 'required',
])){
echo view("team/Templates/header_panel");
echo view("team/navigation", $data);
echo view("team/sidebar", $data);
echo view("team/addpage", $data);
echo view("team/Templates/footer_panel");
}
else {
if($this->pageModel->save) {(
[
'p_name' => $this->request->getVar('p_name', FILTER_SANITIZE_STRING),
'p_description' => $this->request->getVar('p_description'),
'p_date' => date("Y-m-d h:i:s"),
'p_slug' => strtolower(url_title($this->request->getVar('p_name'))),
]
);
$this->session->setTempdata('success', 'Page Created successfully', 3);
return redirect()->to(base_url()."/admin/pages");
}
else {
$this->session->setTempdata('error', 'Unable to create page', 3);
return redirect()->to(current_url());
}
}
Model for this entire code
namespace App\Models;
use CodeIgniter\Model;
class PageModel extends Model {
protected $table = 'tblpages';
protected $allowedFields = ['p_name', 'p_description', 'p_date', 'p_slug'];
public function getPages($slug = null) {
if(!$slug) {
return $this->findAll();
}
return $this->asArray()
->where(['p_slug' => $slug])
->first();
}
public function updateContent($pageContent, $id) {
$builder = $this->db->table('tblpages');
$builder->where('id', $id);
$result = $builder->update($pageContent);
if($this->db->affectedRows() > 0) {
return true;
} else {
return false;
}
}
// Delete Page
public function deletePage($id) {
$builder = $this->db->table('tblpages');
$builder->where('id', $id);
$builder->delete();
}
}
Please help me on this one. Thanks everyone in advance!
I believe this is the culprit in both controllers
'p_description' => htmlentities($this->request->getVar('p_description', FILTER_SANITIZE_STRING))
According to PHP manual, FILTER_SANITIZE_STRING:
Strip tags and HTML-encode double and single quotes, optionally strip or encode special characters.
Since you want to keep the HTML markup, simply remove the FILTER_SANITIZE_STRINGS filter and you should be good to go.
Another problem with your view file is that your text editor has two id's: editor1 and pContent`
<textarea id="editor" name="p_description" class="form-control" id="pContent" cols="10" rows="10" placeholder="Write something here.." required><?= set_value('p_description'); ?></textarea>
Remove the extra id, and everything should be fine.
Edit about the create code not working
In your addPage controller, I noticed this:
if($this->pageModel->save) {([
'p_description' => ...,
])
}
Note that that's not the same as
if($this->pageModel->save([
'p_description' => '...',
])) {
// ...
}

Yii2 Render widget dynamically

I would like to render JQuery UI sortable list (I am using Yii2 JUI widget), to be populated with data from database table. I am passing data from database to the view and have it in a variable. The item HTML structure looks like this:
<div class="row row-item dist simple-border">
<div class="col-md-4">
<img alt="Bootstrap Image Preview" src="<IMAGE_PATH>" />
</div>
<div class="col-md-8">
<h4>
<ITEM DESCRIPTION>
</h4>
</div>
</div>
My question is: What is the best way to populate items inside the Widget, as it is impossible to execute php code within.
<?= yii\jui\Sortable::widget([
'items' => [
------<expected foreach php loop for each model>------
['content' =>
<This is where one HTML item goes>
],
------<end foreach>------
],
'options' => ['class' => 'connectedSortable',],
'clientOptions' => ['cursor' => 'move', 'connectWith' => '.connectedSortable']
]) ?>
My first idea was to create a function that returns item content as a string, but it doesn't seem like a good, efficient practice. Any ideas would be greatly appreciated. Regards.
EDIT: So far, I have created a function, which renders mentioned above items by concatenation. Still, I don't think this is the proper way to do it. I am still new to Yii and would be thankful for any tips. Regards.
I have found such solution for my problem, feel free to review and improve it.
Controller
public function actionIndex()
{
$searchModel = new Exchange();
$dataProvider = $searchModel->getOwnerItems(Yii::$app->request->queryParams);
$ownerItems = $this->getOwnerItems($dataProvider);
return $this->render('index', [
'ownerItems' => $ownerItems,
]);
}
protected function getOwnerItems($dataProvider){
$items=array();
foreach($dataProvider->models as $model){
$item=array('content' => '<div class="row row-item dist simple-border"> <div class="col-md-4"> <img alt="Bootstrap Image Preview" src="uploads/'.$model->image.'" /> </div> <div class="col-md-8"> <h4>'. $model->name .'</h4> </div> </div>');
array_push($items,$item);
}
return $items;
}
View
<?= yii\jui\Sortable::widget([
'items' => $ownerItems,
'options' => ['class' => 'connectedSortable',],
'clientOptions' => ['cursor' => 'move', 'connectWith' => '.connectedSortable']
]) ?>
I am aware of possible imperfection of this solution, but I have no other ideas at the moment. Regards

Listview and custom dataprovider search yii2

I am working on a project in which to display some data i am using a custom query and saving those data in dataProvider. Passing that dataProvider to view file and displaying using a Listview. just like below
<nav class="navbar navbar-fixed-top">
<form class="navbar-form navbar-left search-form" action="">
<div class="form-group"><input type="text" class="form-control app-search" placeholder="Search">
</div>
</form>
</nav>
<div class="panel-group" id="accordion">
<?= \yii\widgets\ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => 'eventlistview',
'layout' => "{items}",
]); ?>
</div>
I want to implement a search bar for that Listview. I am not using any SearchModel so i am confused that how can i do that?
Here is my action code.
public function actionEvent()
{
$this->layout = 'app';
if(isset($_GET['latitude']) && isset($_GET['longitude'])){
$query = new Query();
$query ->select(['e.*','COUNT(d.event_id) as checkins' ,'o.clubname',new Expression("case when c.id is not null then 1 else 0 end is_checkedin")])
->from('event e')
->innerJoin('organiser o', 'e.organiser_id = o.organiser_id')
->leftJoin('checkin c', 'c.event_id = e.id and c.user_id ='.$_GET['user_id'])
->leftJoin('checkin d', 'd.event_id = e.id' )
->where('e.interest_id IN
( SELECT area_intrest.id FROM area_intrest, user WHERE FIND_IN_SET(area_intrest.id,user.area_intrest) AND user.id='.$_GET['user_id'].')')
->groupBy('e.id');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
}
return $this->render('event' ,['dataProvider' => $dataProvider]);
}
I am just confused because i am not using any search model here so i dont know how can i search using title of the event.
In view you can use an active form for sending the value
<?php
$form = ActiveForm::begin(['id' => 'my-form',
'method'=>'get',
'action' => Url::to('your-controller/event')]);
?>
<input type="text" class="form-control app-search" name="my_search" placeholder="Search">
<?= Html::submitButton('search') ?>
<?php ActiveForm::end(); ?>
in your actionEvent you can
$this->layout = 'app';
if (isset($_GET('my_search')) {
// perform what you nedd ..
}
if(isset($_GET['latitude']) && isset($_GET['longitude'])){

Laravel (php) save search options

So i am using laravel 5.2 and i am building a search form, there is multiple search queries and options.
I have been wracking my head trying to think of ways to save the users search and auto fill the form when they visit the search page OR even auto search when they visit it.
So far I have been setting the GET's as variables and auto fill in the text fields but that only lasts for the time they are on the page which is not what i am after,
I have thought about saving the gets into the database as separate fields and when they search and pulling them when they are on the page and filling in each field but then how do I auto search?
Or do I save it as 1 string as the get from the URL eg, u=username&p=postcode
and set the route up to check if the user has a search saved and if they visit /search they get redirected to the url+ get options saved in the db. (no clue how to do this either.)
Now the hardest part even with the gets I have fields that are multiple select like genders and sort by. How do you auto fill in those?
Below is my code for just the form
<?php
if(isset($_GET['u'])) { $username = $_GET['u']; } else { $username = ''; }
if(isset($_GET['p'])) { $postcode = $_GET['p']; } else { $postcode = ''; }
if(isset($_GET['o'])) { $orderby = $_GET['o']; } else { $orderby = ''; }
?>
{{ Form::open(['method' => 'GET']) }}
<div id="filter-panel" class="filter-panel collapse in">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-inline" role="form">
<div class="row">
<div class="col-xs-6 col-sm-2">
{{ Form::input('search', 'u', $username, ['class' => 'form-control input-sm', 'placeholder' => 'username...']) }}
</div><!-- form group [search] -->
<div class="col-xs-6 col-sm-2">
{{ Form::input('search', 'p', $postcode, ['class' => 'form-control input-sm', 'placeholder' => 'postcode...']) }}
</div><!-- form group [search] -->
<div class="col-xs-6 col-sm-3">
<select id="attractedToGender" multiple="multiple" name="g[]" class="input-sm" >
<option value="1">Females</option>
<option value="2">Males</option>
<option value="3">Others</option>
</select>
</div><!--END form-group col-xs-6 col-sm-4-->
<div class="col-xs-12 col-sm-3">
<select id="pref-orderby" class="input-sm" name="o[]" multiple="multiple">
<option value="1">Photo Only</option>
<option value="2">User Type</option>
<option value="3">Last Online</option>
</select>
</div> <!-- form group [order by] -->
<div class="col-xs-6 col-sm-2 pull-right text-right">
{{Form::button('<i class="glyphicon glyphicon-search"></i> Search', array('type' => 'submit', 'class' => 'btn btn-primary btn-sm', 'style' => 'margin:0;'))}}
</div><!--END form-group col-xs-6-->
</div>
</form>
</div>
</div>
</div>
{{ Form::close() }}
There are few ways to do that. The best ways are dedicated model and saving data as JSON object.
Model. You can create dedicated table with User has many Searches relationship. And just save object into this table.
JSON. You can serialize object with ->toJson() method and persist in in a users table. Just add json type column:
$table->json('options');
In both cases you're working directly with the object.

Laravel 4, ->withInput(); = Undefined offset: 0

I have had a lengthy search both here and the Laravel forums, but i can't find an answer to this problem. ->withInput() coughs up an Undefined offset: 0.
For Context:
Controller
public function getJobs()
{
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$result = $query->get();
return View::make('jobsearch.search', array('position_options' => $position_options, 'category_options' => $category_options, 'location_options' => $location_options))->withInput();
}
View
<form action="{{ action('JobsearchController#getJobs') }}" method="post">
<div class="row">
<div class="large-8 columns">
<input type="text" name="realm" placeholder="Keywords/Skills" />
</div>
<div class="large-4 columns">
{{ Form::select('category', $category_options , Input::old('category')) }}
</div>
</div>
<div class="row">
<div class="large-4 columns">
{{ Form::select('location', $location_options , Input::old('location')) }}
</div>
<div class="large-4 columns">
{{ Form::select('type', $position_options , Input::old('type')) }}
</div>
<div class="large-4 columns">
<input type="submit" value="Search" style="width:100%; padding-top: .5rem;
padding-bottom: .5rem;" class="button border-btn" />
</div>
</div>
</form>
Now according to the documentation there should not be an issue, and the page loads fine if the ->withInput(); is removed.
The end goal is to roll in the answer that i received from my previous question Undesired result from db:raw and have a single page that loads the "Filtering" form and displays the relevant results on the reload and remembers the selections in the form.
Thanks in advance.
UPDATE:
Following a comment i have updated the controller and routes, still same result:
routes.php
Route::get('jobs/search', 'JobsearchController#getSearch');
&
Route::post('jobs/search', 'JobsearchController#getJobs');
Controller
public function getSearch()
{
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
return View::make('jobsearch.search', array('position_options' => $position_options, 'category_options' => $category_options, 'location_options' => $location_options));
}
public function getJobs()
{
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
return View::make('jobsearch.search', array('position_options' => $position_options, 'category_options' => $category_options, 'location_options' => $location_options))->withInput();
}
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);

Categories