Codeigniter save form_multiselect into database and set_value - php

i try to save a form_multiselect but it dont save and the value dont select. I hope you can help me please.
Edit: Its working now but only with a single select. I cant select more as one options.
I try this
view
<div class="form-group">
<label class="col-sm-2 control-label" for="field-1"> Team</label>
<div class="col-sm-4">
<?= form_multiselect('teams_id[]', dd2menu('teams', array('teams_id' => 'title')), set_value('teams_id[]', $item->teams_id), 'class="form-control"') ?>
</div>
</div>
Controller
public function manage($id = NULL) {
$data = array();
if ($id) {
$this->{$this->model}->{$this->_primary_key} = $id;
$data['item'] = $this->{$this->model}->get();
if (!$data['item'])
show_404();
} else {
$data['item'] = new Std();
}
$this->load->library("form_validation");
$this->{$this->model}->custom_select = 'users.*, teams.title as teams';
$this->{$this->model}->joins = array( 'teams' => array('teams.teams_id = users.teams_id', 'inner'));
if ($this->form_validation->run() == FALSE)
$this->load->view($this->module . '/manage', $data);
else {
$this->users_model->teams_id = $this->input->post('teams_id');
$this->{$this->model}->save();
redirect('admin/' . $this->module);
}
}
Model
class Users_model extends CI_model
{
public $_table = 'users';
public $_primary_keys = array('user_id');
}
I cant find the error because its working if i one select. But i can select more as one options.

If found the fix in the other code from NikuNi.
Now its save 1 or 1,2 in the Database.
Controller
if( is_array( $this->input->post('teams_id') ) ) {
$this->{$this->model}->teams_id = join(",", $this->input->post('teams_id'));
} else {
$this->{$this->model}->teams_id = $this->input->post('teams_id');
}
$this->form_validation->set_rules('teams_id[]', 'teams_id', 'trim');

Related

Fetch data from DB with CodeIgniter

I need help fetching data from database and display them in view.
My DB name is directory and table usernames that includes:id,title,body,slug,username,platform,gender,age and created_at.
I used foreach to display all posts from database, but i want to display now a specific post based on platform.
How can i do it?
This is the code i use to display all usernames from the database ordered by id:
<div class="col-md-6 mb-4">
<div class="card">
<div class="card-body" style="height: 130px;">
<h5 class="card-title"><?php echo $username_data['title']; ?></h5>
<p class="card-text"><?php echo word_limiter($username_data['body'], 24); ?></p>
</div>
<div class="card-footer text-muted">
<div class="row">
<div class="col-6">
<small>Created at: <?php echo $username_data['created_at'];?></small><br>
<strong>Is <?php echo $username_data['gender'];?></strong>
</div>
<div class="col-6 text-right">
View full message
</div>
</div>
</div>
</div>
</div>
This is my model:
<?php
class Usernames extends CI_Controller{
public function index(){
$data['title'] = 'Lastest Posts';
$data['posts'] = $this->post_model->get_usernames();
$this->load->view('templates/header');
$this->load->view('usernames/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL){
$data['post'] = $this->post_model->get_usernames($slug);
$query = $this->db->get('usernames');
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('usernames/view', $data);
$this->load->view('templates/footer');
}
public function create(){
$data['title'] = 'Create Post';
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('body','Message','required');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('age','Age','required');
$this->form_validation->set_rules('gender','Gender','required');
$this->form_validation->set_rules('platform','Platform','required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('usernames/create', $data);
$this->load->view('templates/footer');
} else {
$this->post_model->create_username();
redirect('usernames');
}
}
public function snapchat(){
$data['title'] = 'Lastest Posts';
$data['posts'] = $this->post_model->get_usernames();
$this->load->view('templates/header');
$this->load->view('usernames/snapchat', $data);
$this->load->view('templates/footer');
}
}
Model:
<?php
class Post_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_usernames($slug = FALSE){
if($slug === FALSE){
$this->db->order_by('usernames.id', 'DESC');
$query = $this->db->get('usernames');
return $query->result_array();
}
$query = $this->db->get_where('usernames', array('slug' => $slug));
return $query->row_array();
}
public function create_username(){
$slug_link = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(16))), 0, 16);
$slug = url_title($this->input->post('title').'-'.$slug_link);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'platform' => $this->input->post('platform'),
'age' => $this->input->post('age'),
'gender' => $this->input->post('gender'),
'username' => $this->input->post('username')
);
return $this->db->insert('usernames', $data);
}
}
Everything is working fine, but i don't know really how to fetch those data.
I need that in this specific page ('telegram.php'), show all rows that includes Telegram from platform.
As mentioned before, my database is structured like this:
directory(DB Name)
usernames(table name)
->id->title->body->slug->user
public function get_usernames_from_platform($platform){
if(!empty($platform)){
$this->db->where('platform',$platform);
$this->db->order_by('usernames.id', 'DESC');
$query = $this->db->get('usernames');
return $query->result_array();
}
return array();
}
Add the method, to your Model and call it to fetch the corresponding data in the corresponding method in your controller.
It seems to be missing its constructor $this->load->model('post_model');

SilverStripe 3.6.2 - Sorting Paginated Data Objects by Dropdown selection triggers 404 error

A couple years ago, I setup a paginated list of News Article Pages that were sorted by year based on a dropdown field selection: SilverStripe - Create pagination based on dropdown selection
I'm now trying to do the same thing but this time, the News Articles are data objects. Otherwise, everything else is the same.
The problem is I cannot get it to work this time and I'm not sure why. I'm following the same steps but when I select a year from the dropdown, I am taken to a 404 page on my site, and, in the Network tab in Chrome, there is a 404 status for the url:
I can see that the year value is not getting passed to the page's code for processing, but I'm not sure why as it did work -- and still works -- on the other SilverStripe site I was working on from the old post I linked to.
Here is the code that I have right now:
;(function($) {
$(function(){
// hide form actions, as we want to trigger form submittal
var newsYearFilterForm = $("#Form_YearFilterForm");
// automatically when dropdown changes
newsYearFilterForm.find(".Actions").hide();
// bind a change event on the dropdown to automatically submit
newsYearFilterForm.on("change", 'select[name="Year"]', function(e){
newsYearFilterForm.submit();
});
// handle pagination clicks
$("body").on("click", "a.pagination", function (e) {
e.preventDefault();
// $("#ArticleList").addClass("loading");
$.get(
$(this).attr("href"),
function(data, status, xhr){
$("#ArticleList").replaceWith($(data));
}
);
return false;
});
});
})(jQuery);
NewsLandingPage.php
<?php
class NewsLandingPage extends Page
{
private static $description = 'News Landing page.';
private static $db = array();
private static $has_one = array();
}
class NewsLandingPage_Controller extends Page_Controller
{
private static $allowed_actions = array(
'renderNewsItem',
'YearFilterForm',
'year',
);
public function init()
{
parent::init();
}
private static $url_handlers = array(
'$NewsItem!' => 'renderNewsItem',
);
public function getAllNews()
{
$newsList = NewsItem::get()->sort('NewsDate', 'DESC');
return new PaginatedList($newsList, $this->getRequest());
}
public function renderNewsItem(SS_HTTPRequest $request)
{
$newsItemName = $request->param('NewsItem');
if ($newsItemName != "") {
$newsItem = NewsItem::get()->filterAny(array(
'NewsItemSlug' => $newsItemName
))->first();
if ($newsItem) {
$arrayData = array(
'NewsItem' => $newsItem,
);
return $this->renderWith(array('NewsArticle', 'Page'), new ArrayData($arrayData));
} else {
return $this->httpError(404);
}
}
}
public function handleYearRequest(SS_HTTPRequest $request)
{
$year = $request->param('ID');
$data = array(
'Year' => $year,
'PaginatedReleases' => $this->PaginatedReleases($year)
);
if ($request->isAjax()) {
// in case of an ajax request, render only the partial template
return $this->renderWith('ArticleList', $data);
} else {
// returning an array will cause the page to render normally
return $data;
}
}
//creates a form to filter through news releases by year
public function YearFilterForm()
{
// get an array of all distinct years
$list = SQLSelect::create()
->addFrom('NewsItem')
->selectField('YEAR("NewsDate")', 'Year')
->setOrderBy('Year', 'DESC')
->execute()->column('Year');
// create an associative array with years as keys & values
$values = array_combine($list, $list);
// our fields just contain the dropdown, which uses the year values
$fields = FieldList::create(array(
DropdownField::create(
'Year',
'',
$values,
$this->getRequest()->param('ID')
)->setHasEmptyDefault(true)
->setEmptyString('Show all')
->setAttribute('data-urlpattern', $this->Link('year') . '/YYYY')
));
$actions = new FieldList(
FormAction::create('doFilter', 'Submit')
);
return Form::create($this, 'YearFilterForm', $fields, $actions);
}
public function year()
{
return $this->handleYearRequest($this->request);
}
public function index()
{
return $this->handleYearRequest($this->request);
}
//redirects to the proper url depending on which year is selected for sorting news
public function doFilter($data, $form)
{
if (empty($data['Year'])) {
return $this->redirect($this->Link());
} else {
return $this->redirect($this->Link('year/' . $data['Year']));
}
}
//created a paginated list of news released by year
public function PaginatedReleases($year = null)
{
$list = NewsItem::get()->sort('NewsDate', 'DESC');
if ($year) {
$list = $list->where(array('YEAR("NewsDate") = ?' => $year));
}
return PaginatedList::create($list, $this->getRequest())->setLimitItems(10);
}
}
NewsItem.php
class NewsItem extends DataObject{
private static $db = array(
'NewsName' => 'Varchar(255)',
'NewsItemSlug' => 'Varchar(250)',
'NewsDate' => 'SS_Datetime',
'NewsLocation' => 'Varchar(255)',
'NewsArticle' => 'HTMLText',
'NewsArticleSummary' => 'HTMLText',
'SortOrder' => 'Int',
);
private static $summary_fields = array(
'NewsName',
'NewsDate',
'NewsItemSlug',
);
private static $has_one = array(
'NewsImage' => 'Image',
'NewsUrlForHomePage' => 'SiteTree',
'Page' => 'Page'
);
public function onBeforeWrite() {
parent::onBeforeWrite();
if ($this->NewsItemSlug == ""){
$linkName = $this::getLinkName();
if ($linkName == ""){
$linkName = str_replace(array(" ",":","%","$","#","#","!","^","&","*","(",")","'",";","<",">","/","?","[","]","{","}","\\","|","`","~","=","+","’",",","."),"-",strtolower(str_replace("&","and",str_replace(".","",$this->NewsName))));
}
$this->NewsItemSlug = $linkName;
} else {
$this->NewsItemSlug = str_replace(array(" ",":","%","$","#","#","!","^","&","*","(",")","'",";","<",">","/","?","[","]","{","}","\\","|","`","~","=","+","’",",","."),"-",strtolower(str_replace("&","and",str_replace(".","",$this->NewsItemSlug))));
}
}
public function getLinkName() {
if ($this->NewsItemSlug != "" && !is_null($this->NewsItemSlug)){
return $this->NewsItemSlug;
}
return str_replace(" ","-",strtolower(str_replace("&","and",$this->NewsName)));
}
public function LinkingMode() {
return Controller::curr()->getRequest()->param('ID') == $this::getLinkName() ? 'current' : 'link';
}
public function Link() {
$newsLandingPage = NewsLandingPage::get()->first();
$linkName = $this::getLinkName();
if ($linkName){
return $newsLandingPage->Link($linkName);
} else {
return false;
}
}
public function canView($member = null){
return true;
}
public function canEdit($member = null) {
return true;
}
public function canCreate($member = null) {
return true;
}
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeFieldFromTab("Root.Main","PageID");
return $fields;
}
}
class NewsItemAdmin extends ModelAdmin {
private static $managed_models = array(
'NewsItem',
);
private static $url_segment = 'NewsItems';
private static $menu_title = 'News';
}
NewsLandingPage.ss
<% include BreadCrumbs %>
<div class="container container-intro-copy" style="background-color:#fff;opacity:1.0;">
<h1 class="intro-copy h1">$H1</h1>
<div class="intro-copy">$Content</div>
$YearFilterForm
<% include NewsList %>
</div>
NewsList.ss
<div id="ArticleList" class="container careers-list">
<div class="row">
<% loop $PaginatedReleases %>
<div class="career-item col-lg-10 col-lg-offset-1 col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-xs-12 item bio-detail aos-init aos-animate" data-aos="fade-up" data-aos-delay="200" style="margin-top:30px;">
<div class="box-for-resources top-box-style">
<div class="box-resources-left"><img src="$NewsImage.URL" class="image-resources-cmmm"></div>
<div class="box-resources-right">
<h3 class="name left" style="color:#002f65 !important; float: left; clear: both;">$NewsName</h3>
<p class="box-resource-copy text-date"><em>$NewsDate.FormatI18N('%B %d, %Y') ($NewsLocation)</em></p><br />
<div class="careers-copy">$NewsArticleSummary</div><br />
Read Article
</div>
</div>
</div>
<% end_loop %>
</div>
</div>
The news page successfully loads all the articles by default and the links to each article work properly. The dropdown form has the correct list of years based on the range the articles have.
I think you have a conflict with your url_handlers and the actions you're calling on the controller.
'$NewsItem!' => 'renderNewsItem',
The above line matches all actions to renderNewsItem. Eg. yoursite.test/controller/YearFilterForm will also be matched by this…
You should add some static part to your handler that displays a news item. So your url_handlers would be:
'show/$NewsItem!' => 'renderNewsItem',
Then you'd have to adjust your NewsItem->Link method accordingly.
I also suggest you use the URLSegmentFilter to create your slugs… eg.
public function onBeforeWrite() {
parent::onBeforeWrite();
// only rebuild the slug when news-name has changed
if ($this->isChanged('NewsName', DataObject::CHANGE_VALUE)) {
$filter = URLSegmentFilter::create();
$t = $filter->filter($this->NewsName);
// Fallback to generic name if path is empty (= no valid, convertable characters)
if (!$t || $t == '-' || $t == '-1') {
$t = "news-{$this->ID}";
}
$this->NewsItemSlug = $t;
}
}

database value how to pass dropdown list in codeigniter

How to pass value to drop down list in CodeIgniter?
This is my view file HTML code:
<div class="form-group">
<select name="department" id ="department">
<?php
foreach($dept as $country)
{
echo '<option value="'.$country['dept_id'].'">'.$country['managers_name'].'</option>';
}
?>
</select>
</div>
This is my controller code:
public function department()
{
$this->load->model('insert_model');
$data['dept'] = $this->insert_model->category_name_get();
}
This is my model file code:
function category_name_get()
{
$query = $this->db->get('dept');
if ($query->num_rows >= 1)
{
foreach($query->result_array() as $row)
{
$data[$row['dept_id']]=$row['managers_name'];
}
return $data;
}
}
I think you are searching for Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
In your case $data contains the department list in it as an array.
In Your COntroller file you will get all date on $data['dept'] that returned from model.
public function department()
{
$this->load->model('insert_model');
$data['dept'] = $this->insert_model->category_name_get();
$this->load->view('view_file_name',$data);
}
In your view file you will get this data
Just do print_r($dept); and check array..
you will find more info from this link
Probably your model is not returning "proper" data for your view. Perhaps something like this:
function category_name_get()
{
$data = array();
$query = $this->db->get('dept');
if ($query->num_rows >= 1)
{
foreach($query->result_array() as $row)
{
$data[] = array(
'dept_id' => $row['dept_id'],
'managers_name' => $row['managers_name']
);
}
}
return $data;
}
function category_name_get()
{
$query = $this->db->get('dept');
if ($query->num_rows() >= 1)
{
foreach($query->result_array() as $row)
{
$data[$row['dept_id']]=$row['managers_name'];
}
return $data;
}
}
Use num_rows() instead of num_rows. I hope it works now.

Codeigniter Bootstrap Alert not Working

I'm trying to make alert with cross sign. Unfortunately cross sign not working. I have included jquery before bootstrap.js. Here is my model. Thanks in Advance
public function create(){
$data = array('name'=> $this->input->post('name'));
$this->db->insert('dbname', $data);
echo'
<div class="alert alert-success">
×You have successfully posted
</div>
';
exit;
}
Change this to
×You have successfully posted
this
×You have successfully posted
And as well as use Model to write data into database. Use follows
In controller
public function create(){
$this->load->model('Model_name');
$result = $this->Model_name->insert_data();
if($result == 1)
{
?>
<div class="alert alert-success">
×You have successfully posted
</div>
<?php
}
else
{
?>
<div class="alert alert-error">
×Failed to poste
</div>
<?php
}
}
In Model
public function insert_data()
{
$data = array(
'name'=> $this->input->post('name')
);
if(!$this->db->insert('dbname', $data))
{
return $log = 0;
}
else
{
return $log = 1;
}
}

Laravel 4 - view is rendered in one function but not in another

Ok here is the test controller:
class TestController extends BaseController {
public function __construct() {
ini_set("display_errors", true);
}
private $turnoverPerFranchise = array(
0 => 't1',
1 => 't2'
);
private $turnoverPerShop = array(
0 => 's1',
1 => 's2'
);
public function getTurnover() {
$formData = array();
$formData['shops'] = 'shosp dropdown';
$form = View::make('test.form', $formData);
$data2['content'] = $form;
return View::make('test/template', $data2);
}
public function postTurnover() {
echo 'post';
$formData = array('a');
$formData['filteredData'] = $this->getFiltered();
// if not set index shops. then it displays error - its how is expected
$data['content'] = View::make('test.form', $formData);
return View::make('test/template', $data);
}
private function getFiltered() {
$data2['totalsTable'] = $this->getTotalsView();
$data2['franchiseBlocks'] = array();
foreach ($this->turnoverPerFranchise as $franchiseId => $franchiseTurnover) {
$franchiseData['franchise'] = $franchiseTurnover;
$franchiseData['systemCurrency'] = '$';
$franchiseData['shopViews'] = array();
foreach ($this->turnoverPerShop as $shopId => $shopTurnover) {
if ($shopTurnover['franchiseId'] == $franchiseId) {
$franchiseData['shopViews'][] = 'shop view';
}
}
$data2['franchiseBlocks'][] = View::make('test.filteredData.franchise', $franchiseData);
//$data2['franchiseBlocks'][] = 'aa';
}
echo count($data2['franchiseBlocks']) . '<br>';
return View::make('test.filteredData.main', $data2); // same
}
/**
* Gets table of filteredData totals
* #return object
*/
private function getTotalsView() {
$dataTotals = array();
$dataTotals['totals'] = 'bla bla bla';
$dataTotals['systemCurrency'] = '$';
return View::make('test.filteredData.totalsTable', $dataTotals);
}
public function getMain() { // works
$data2['franchiseBlocks'] = array(1 => 'a');
return View::make('test.filteredData.main', $data2); // the same view in getFiltered is not displayed
}
}
If I call function postTurnover()
then it is rendered
post2 and the submit button. 2 means that there are 2 items for view to run in foreach loop.
When I run function getMain()
then the view renders perfectly fine.
View test/filteredData/main.blade.php is simple:
<br>
main
#foreach ($franchiseBlocks as $franchise)
<strong>franchise block</strong>
{{ $franchise }}
#endforeach
view test/filteredData/franchise.blade.php
franchise
#foreach ($shopViews as $shop)
<strong>aaa</strong>
#endforeach
Other views are probably not important. But if they are I will copy them.
Can you tell why can it not display as expected?
found the problem - was not using that data in test/filteredData/form.blade.php
had to put:
{{ $filteredData; }}

Categories