Codeigniter: Can edit form and insert form use the same validation? - forms

This is my function validation for insert article. But when I work with edit article also have form validation and with same condition. So I would like to use only one function validation instead of copy and paste.
function article_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Article Name','required|trim|xss_clean');
$this->form_validation->set_rules('content','Article body','required|trim|xss_clean');
if($this->form_validation->run())
{
$this->load->model('article');
$this->article->insert_article();
redirect('article');
}
else
{
$this->load->view('page/insert');
}
}

Try creating an is_valid method in you controller, call it anywhere in your controller, just make your is_valid function private to avoid being routed.
Class Articles {
private function is_valid(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name','Article Name','required|trim|xss_clean');
$this->form_validation->set_rules('content','Article body','required|trim|xss_clean');
return $this->form_validation->run();
}
public function create_article()
{
if($this->is_valid()){
//save in DB
}
}
public function edit_article($id)
{
if($this->is_valid()){
//save in DB
}
}
}

Related

CakePhp3 redirect from private method

I have this problem with CakePhp3:
In my controller I would like to do something like this:
class MyController extends Controller
{
public function myAction1(){
$this->initData();
/* more code here */
}
public function myAction2(){
$this->initData();
/* more code here */
}
public function myAction3(){
$this->initData();
/* more code here */
}
/* more actions here */
private function initData(){
if ($this->validData()){
/* complex code to initalize data */
}else{
/* REDIRECT TO FAIL URL */
}
}
private function validData(){
/* complex code to validate data */
return $valid;
}
}
My question is:
What code should I use instead of
/* REDIRECT TO FAIL URL */
to redirect the user to a different url?
Using:
return $this->redirect($url);
inside initData (ofcourse) doesn't work and I would like not to handle the redirect inside every action.
There's no built-in support for that (yet). It should be simple enough to implement this on your own, you could for example overwrite Controller::invokeAction() to catch redirect exceptions, and make it return redirect responses accordingly, something like:
public function invokeAction()
{
try {
return parent::invokeAction();
} catch (\Cake\Routing\Exception\RedirectException $exception) {
return $this->redirect($exception->getMessage(), $exception->getCode());
}
}
private function initData()
{
if ($this->validData()) {
// ....
} else {
throw new \Cake\Routing\Exception\RedirectException(
\Cake\Routing\Router::url([/* ... */]), // redirect URL
302 // HTTP status code
);
}
}

Laravel 5.3 : eager load with many to many relationship

I'm trying to use eloquent to retrieve 5 last messages and display them on the dashboard.
The problem is, I need to get those messages depending on the user->role. But the message is linked to an update log. This update log is use to dispatch every dashboard message, sms to notify and email.
There is how it work :
User
public function role()
{
return $this->belongsTo(Role::class);
}
Role
public function updatelogs()
{
return $this->belongsToMany(Updatelog::class, 'role_updatelog');
}
public function users()
{
return $this->hasMany(User::class);
}
Updatelog
public function roles()
{
return $this->belongsToMany(Role::class, 'role_updatelog');
}
public function dashboard_message()
{
return $this->hasOne(DashboardMessage::class);
}
DashboardMessage
public function updatelog()
{
return $this->belongsTo(Updatelog::class);
}
There is what I tried:
$dashmessages = DashboardMessage::with(array('updatelog' => function($q) use($user) {
$q->with(array('roles' => function($q2) use($user) {
$q2->whereHas($user->role_id);
}));
$q->whereHas('institution');
}))->with('updatelog.institution.rate_grids')->orderBy('updated_at', 'DESC')->take(5)->get();
I'm getting the last 5 DashboardMessages without the role constraint. What am I doing wrong?
EDIT---------------------------------------------------
I just tried something else and it work perfectly:
$updatelog = Updatelog::whereHas('roles', function ($query) use($user) {
$query->where('role_id', $user->role_id);
})
->whereHas('dashboard_message')
->with('dashboard_message')
->whereHas('institution')
->with('institution')
->with('rate_grid')
->take(5)->get();

Even i install plugin but install method not called in pimcore

Note here install and uninstall method. I am writing code for creating table. But i want to call this install method as plugin installed automatically, and it should behave this way as pimcore doc suggest.
namespace Newsletter;
use Pimcore\API\Plugin as PluginLib;
use Pimcore\Db;
class Plugin extends PluginLib\AbstractPlugin implements PluginLib\PluginInterface
{
public function init()
{
parent::init();
// register your events here
// using anonymous function
\Pimcore::getEventManager()->attach("document.postAdd", function ($event) {
// do something
$document = $event->getTarget();
});
// using methods
\Pimcore::getEventManager()->attach("document.postUpdate", [$this, "handleDocument"]);
}
public function handleDocument($event)
{
// do something
$document = $event->getTarget();
}
public static function install()
{
$this->dbConnection = Db::getConnection();
$this->dbConnection->query("CREATE TABLE IF NOT EXISTS newsLetter(id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, cname VARCHAR(100) NOT NULL)");
return true;
}
public static function uninstall()
{
// implement your own logic here
$this->dbConnection->query("DROP TABLE newsLetter");
Db::close(); // closes connection
return true;
}
public static function isInstalled()
{
// implement your own logic here
return true;
}
}
You should implement the isInstalled method and in that method check if the table was already created and return false if not.
Then the user must click on the install button to actually trigger the installation.
Since you are returning true in isInstalled method, the system never triggers the installation.

Can't get mysqli identifier from another class

I have two classes: one for sql and one for authentication. These are separate files that only "come together" by an autoloader in another file (index.php). The sql class looks like this:
class aF_sql {
public static $open;
public static $char;
public static $close;
public static function open() {
global $config;
self::$open = mysqli_connect($config['aF_sql_host'], $config['aF_sql_user'], $config['aF_sql_pass'], $config['aF_sql_data']);
if(!self::$open) {
die('<b>ERROR (/core/sql/1): Could not initialize database connection</b>');
}
self::$char = mysqli_set_charset(self::$open, $config['aF_sql_char']);
if(!self::$char) {
die('<br>ERROR (/core/sql/2): Could not set database charset</br>');
}
return TRUE;
}
public static function close() {
self::$close = mysqli_close(self::$open);
if(!self::$close) {
die('<b>ERROR (/core/sql/3): Could not close database connection');
}
return TRUE;
}
}
Everything works fine until here. I open the sql connection by using the class::open(); method and I close it by using class::close();. Then, I have a file that should help me check some login details (the auth class). For now, all I want is an echo of the submitted username. Here is the content:
class aF_auth {
public static function login() {
echo mysqli_real_escape_string(aF_sql::open, $_POST['username']);
}
}
Thisis what the error says: Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given... What should I use as an identifier to be able to perform queries? As you know, mysqli requires the connection identifier.
Thanks a million
Ok, I figured it out! Instead of returning TRUE in the class, I return self::$open. This way, I can use aF_sql::$open everywhere in the software and it refers to the connection identifier. With other words, it didn't work because I was not returning the variable in the class...
class aF_sql {
public static $open;
public static $char;
public static $close;
public static function open() {
global $config;
self::$open = mysqli_connect($config['aF_sql_host'], $config['aF_sql_user'], $config['aF_sql_pass'], $config['aF_sql_data']);
if(!self::$open) {
die('<b>ERROR (/core/sql/1): Could not initialize database connection</b>');
}
self::$char = mysqli_set_charset(self::$open, $config['aF_sql_char']);
if(!self::$char) {
die('<br>ERROR (/core/sql/2): Could not set database charset</br>');
}
return self::$open;
}
public static function close() {
self::$close = mysqli_close(self::$open);
if(!self::$close) {
die('<b>ERROR (/core/sql/3): Could not close database connection');
}
return TRUE;
}
mysqli_real_escape_string(aF_sql::$open, $_POST['username']);
That's it...

Laravel redirect to post method

To stay basic I would like to create a bookmark app
I have a simple bookmarklet
javascript:location.href='http://zas.dev/add?url='+encodeURIComponent(location.href)
I created a rest controller
<?php
use zas\Repositories\DbLinkRepository;
class LinksController extends BaseController {
protected $link;
function __construct(DbLinkRepository $link) {
$this->link=$link;
// ...
//$this->beforeFilter('auth.basic', array('except' => array('index', 'show', 'store')));
// ...
}
public function index()
{
//return Redirect::to('home');
}
public function create()
{
}
public function store()
{
return 'hello';
//$this->link->addLink(Input::get('url'));
//return Redirect::to(Input::get('url'));
}
public function show($id)
{
//$url = $this->link->getUrl($id);
//return Redirect::to($url);
}
public function edit($id)
{
}
public function update($id){
}
public function destroy($id){
}
}
in the routes.php, I created a ressource
Route::resource('links','LinksController');
and as I want to redirect /add to the store method I added
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
but it never display the hello message, in place it redirects me to
http://zas.dev/links
I also tried with
return Redirect::route('links.store');
without much success
thanks for your help
Ok I now get what you are trying to do. This will work:
Route::get('add', 'LinksController#store');
Remove:
Route::resource('links','LinksController');
and remove:
Route::get('/add',function(){
return Redirect::action('LinksController#store');
});
Sorry it took so long!
The problem is that once you Redirect::, you loose all the Input values, so you should manually give them to your controller when you do the redirect, like so :
Redirect::route('links.store', ["url" => Input::get("url")]);
Finally add an $url parameter to your store method to receive the value we give it in the previous method, like this :
public function store($url) {
$this->link->addLink($url);
return Redirect::to($url);
}