⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

callback_before_insert inside $crud->getState() not Working



Rodrigo4ever

Rodrigo4ever
  • profile picture
  • Member

Posted 07 July 2017 - 15:55 PM

Olá,

 

Alguém pode me ajudar nesse código abaixo?

(Can anyone help me with this code below?)

 

Problema: Preciso tratar alguns dados antes de submete-los ao banco de dados.
Queria também, só para fim de organização do código, separar as ações dentro de escopos diferentes, exemplo: 

(Problem: I need to handle some data before submitting it to the database.

I also wanted, for the purpose of organizing the code, to separate actions within different scopes, for example:)

if($state === 'list'){
 
  //process any fields before list.
 
  $output = $crud->render(); // not allowed here?
  $this->_example_output($output); // not allowed here?
 
 
}
if($state === 'add'){
   
  //process any fields before add.
 
  $output = $crud->render(); // not allowed here?
  $this->_example_output($output); // not allowed here?
 
}
if($state === 'edit'){
   
  //process any fields before edit.
 
  $output = $crud->render(); // not allowed here?
  $this->_example_output($output); // not allowed here?
 
}
if($state === 'insert'){
 
 //process any fields before insert.
 
  $output = $crud->render(); // not allowed here?
  $this->_example_output($output); // not allowed here?
 
} 

Segue um pedaço do meu código.

Here's a little of my code.

public function index(){
      $crud = new grocery_CRUD();
      echo $state = $crud->getState();
      $state_info = $crud->getStateInfo();

      if($state === 'add'){
	 $crud->unset_jquery();
	 $crud->set_theme('datatables');
	 $crud->set_subject('Adicionar Proximo Sorteio');

         $crud->unset_add_fields('desc_rodada2','foto_premio1','foto_premio2', 'foto_premio3', 'foto_premio4');
	 $crud->fields('data','n_susep', 'desc_rodada', 'separador', 'desc_premio1', 'desc_premio2', 'desc_premio3', 'desc_premio4', 'img_cautela', 'proxExtracao');
	 $crud->field_type('data', 'date');

	 /// Here not Show :( 
         $crud->callback_before_insert(function ($post_array)  {
	   echo "<script>alert('callback_before_insert')</script>";
	   return $post_array;
	 });
      }
      /// Here not Show :(
      elseif($state === 'insert'){
	echo "ENTREI";
	//die();
      }
      
      $output = $crud->render();
      $this->_example_output($output);

}
public function _example_output($output = null){
     .....
}

Can anyone help me with this code below?


Rodrigo4ever

Rodrigo4ever
  • profile picture
  • Member

Posted 10 July 2017 - 19:49 PM

Can anyone help me?

Can anyone help me?


Amit Shah

Amit Shah
  • profile picture
  • Member

Posted 13 July 2017 - 05:34 AM

Bem, meu amigo,
 
Tente e compreenda como quando e como as chamadas para as ações são disparadas. State - add .. representa o estado quando o usuário está tentando carregar o formulário de adicionar. Lá - você certamente será obrigado a definir as condições de pré-forma mostrando. Agora, por que você não consegue ver seu retorno de chamada - porque você considerou registrar o mesmo apenas sob o estado - adicione ... agora quando a dose realmente é chamada? Ele é chamado apenas antes que o usuário esteja tentando inserir ... o estado será - insira ... que, então, quando a função é chamada usando o Ajax - esse registro de retorno de chamada falha ... então você não conseguirá executá-lo.
 
Eu recomendarei deixar o retorno de chamada fora do estado de adição ... e ele deve resolver seu problema.
 
Feliz GCing :)

 

......................

 

Well my friend,

 

Try and understand as when and how the calls to the actions gets triggered. State - add .. represents the state when the user is trying to load the add form. In there - you surely are bound to set the pre-form showing conditions. Now why you not able to see your callback - because u have considered registering the same only under the state - add .. now when dose it actually gets called up ?? It gets called just before the user is trying to insert ... the state will be - insert  .. that then when the function is called using Ajax - that registration of callback fails there .. hence you wont be able to get it running.

 

I will recommend leave the callback outside the add state .. and it should solve your problem.

 

Happy GCing :)


Rodrigo4ever

Rodrigo4ever
  • profile picture
  • Member

Posted 13 July 2017 - 11:43 AM

I will recommend leave the callback outside the add state .. and it should solve your problem.

 

The problem is that none of the functions are working. Neither out of state nor inside.

As I showed in the code above.

 

 

The problem is that none of the functions are working. Neither out of state nor inside. As I showed in the code above.

WHY MY GOD???? :( :( :(

Project stopped because of this, I'm about to leave Grocery Crud aside

 

 

Project stopped because of this, I'm about to leave Grocery Crud aside
 
Project stopped because of this, I'm about to leave Grocery Crud aside
 

 

Why my God?
Why my God

if($state === 'add'){
  /*
  code
  */
  /// Here not Show  
  $crud->callback_before_insert(function ($post_array) {
      echo "<script>alert('callback_before_insert')</script>";
      return $post_array;
   });
}
elseif($state === 'insert'){
    echo "ENTREI";
    //die();
}

public function _callback_before($post_array)
{
      echo "<script>alert('callback_before_insert')</script>";
      // return $post_array;
      return true;
}

Amit Shah

Amit Shah
  • profile picture
  • Member

Posted 14 July 2017 - 05:33 AM

Well my friend - Leaving GroceryCrud or not.. is a call you have to take.

 

There have been thousands of users using the same piece of code and are able to run things very smoothly. I went through your code .. there is nothing that needs to go special about the states you trying to explore with...

 

the whole code can be rewritten in simple piece of code without state...

public function index(){
  	$crud = new grocery_CRUD();
  	echo $state = $crud->getState();
  	$state_info = $crud->getStateInfo();

	//if($state === 'add'){
		$crud->unset_jquery();
		$crud->set_theme('datatables');
		$crud->set_subject('Adicionar Proximo Sorteio');

		$crud->unset_add_fields('desc_rodada2','foto_premio1','foto_premio2', 'foto_premio3', 'foto_premio4');
		$crud->fields('data','n_susep', 'desc_rodada', 'separador', 'desc_premio1', 'desc_premio2', 'desc_premio3', 'desc_premio4', 'img_cautela', 'proxExtracao');
		$crud->field_type('data', 'date');

		/// Here not Show :( 
		$crud->callback_before_insert(function ($post_array)  {
			echo "<script>alert('callback_before_insert')</script>";
			return $post_array;
		});
	//}
	/// Here not Show :(
	//elseif($state === 'insert'){
		echo "ENTREI";
		//die();
	//}

	$output = $crud->render();
	$this->_example_output($output);

}

There are reason why people use state.. specially something like - if user clicked on add.. and you wana log the users activity on that state - it can work that way... or if user clicked on delete and basis of his permission, it may either be deleted permanently or have a flag set some place.. or something like that..

You may explore the states ... its a good idea to understand and use the system to the fullest.. but using it wrongly.. is only going to break your own system. 

 

Whatever codes you used.. they were never intended to be in the state at all..  Had you referenced the documents / examples you would have seen that what you were trying out to achieve with state was absolutely out of need.

 

Anyways, hope you invest good time and learn the system .. understand to use it better...so you can get use it to the max.

 

You can any given point of time go ahead and use any other system you wish to.. but i found GC as 1 of the finest CRUD libraries around and i am with it for years .. and will be with it for years to come.

 

Happy GCing :)


Rodrigo4ever

Rodrigo4ever
  • profile picture
  • Member

Posted 14 July 2017 - 13:46 PM

But, I need to use the status = add or even the status = edit. Why the user clicking add I want to limit some $ crud-> unset_add_fields () fields to addition. As well as adding other fields $ crud-> fields ('data'). And the user trying to save I NEED to do code processing, pick up some fields added to the form and do checks before saving. So I would need the status to be able to show only a few fields and a method that I would process fields before submitting. That's why I tried that solution. Without it my system will not wor


Amit Shah

Amit Shah
  • profile picture
  • Member

Posted 15 July 2017 - 18:37 PM

Well.. unset_add anyways works only when the user is trying to run the add action .. so even if you are not in that state - and u set the unset action - it wont have any impact.. user will never be able to do anything with it. Technically in either of your requirements, i actually don't see any good reason so as to why u need to set it only in unset add / edit .. etc. When you can do the same even without the being in the required state. 

In order to do preprocessing before saving the data - yes .. there is callback before insert feature.. but that again u can declare it even without user not being in any state because the impact of the same will happen only when that even occurs. Without that event, that piece of code is never going to be executed. So again, here - i don't see any need for the same.

We have used the similar requirements all without trying to capture the users state and we have been successful in same yet. And i believe very strongly you too will have good results with it.

 

Request you to understand the logic behind the hooks so u can actually harness the power of the same in the right direction.

 

Happy GCing :)


Rodrigo4ever

Rodrigo4ever
  • profile picture
  • Member

Posted 17 July 2017 - 19:31 PM

After much struggle, I managed to do more or less what I wanted. BUT, the bloody $ crud-> callback_before_insert (array ($ this, '_callback_before')) does not work. Lol What can it be?

public function index(){

		$crud = new grocery_CRUD();
		$crud->unset_jquery();
		echo $state = $crud->getState();
		$state_info = $crud->getStateInfo();

		$crud->set_table('proxsorteios');
		$crud->set_theme('datatables');
		$crud->set_subject('Proximo Sorteio');
		$crud->order_by('id', 'desc');
		$crud->limit(5);
		$crud->columns('id', 'data', 'proxExtracao');
		$crud->set_field_upload('img_cautela','assets/uploads/files/proxsorteios');

		$crud->callback_before_insert(array($this, '_callback_before'));

		if($state === 'add'){
			$crud->unset_add_fields('desc_rodada2','foto_premio1','foto_premio2', 'foto_premio3', 'foto_premio4');
			$crud->fields('data','n_susep', 'desc_rodada', 'separador', 'desc_premio1', 'desc_premio2', 'desc_premio3', 'desc_premio4', 'img_cautela', 'proxExtracao');
			$crud->field_type('data', 'date');

		}
		if($state === 'read'){
			$crud->unset_add_fields('desc_rodada2','foto_premio1','foto_premio2', 'foto_premio3', 'foto_premio4');
		}

		if($state === 'edit'){
			$crud->unset_add_fields('desc_rodada2','foto_premio1','foto_premio2', 'foto_premio3', 'foto_premio4');
			$crud->fields('data','n_susep', 'desc_rodada', 'separador', 'desc_premio1', 'desc_premio2', 'desc_premio3', 'desc_premio4', 'img_cautela', 'proxExtracao');
			// $crud->field_type('data', 'date');
		}



		$output = $crud->render();
		$this->_example_output($output);
  }
	public function _callback_before($post_array)
	 {
		 	 print_r($post_array);
			 echo "<script>alert('Helo')</script>";
			 print "LALALA";// return $post_array;
			//  die();
			//  return false;
	 }
  public function _example_output($output = null)
	{

		$this->load->model("config_model");
		$config_site = $this->config_model->buscaConfig();

		$head = array(
			'author' => 'Rodrigo Barbosa',
			'description' => '',
			'title' => 'Painel de Controle - Site'
		);
		$nav = array(
				'site' => $config_site['site'],
		);

    $this->load->view('head', $head);
    $this->load->view('layout-bootstrap/css/template-bootstrap-css');
    $this->load->view('layout-bootstrap/nav.php', $nav);
    // $this->load->view('dashboard');
    $this->load->view('usuarios',(array)$output);
    $this->load->view('layout-bootstrap/js/template-bootstrap-js');
	}

After much struggle, I managed to do more or less what I wanted. BUT, the bloody $ crud-> callback_before_insert (array ($ this, '_callback_before')) does not work. Lol What can it be?


Amit Shah

Amit Shah
  • profile picture
  • Member

Posted 18 July 2017 - 06:54 AM

well.. i still dont understand why u need to check the state and stuff .. because i dont really see any reason why you should even check in the above code. what i see in the same is unset_add field - this call dont need to be set again and again in edit / read.- why? Cuz library checks for any sort of unset_add only when the add form is to be displayed. 

So leaving it out of state should not do any issue.

 

Now if you want to test callback ..

return false - and it should break insert operation and give u an error.

Also - possible for you to kill the operation using die and see the output in the console.

Either way - u should be able to ensure that the callback is working.

Just printing wont work to comply if the callback is working or not...