I'm trying to make a system where an admin creates a project template, and then templates for both text (limit on characters) and images (height/width and file extension)
When I have one template, the code works perfectly and I can even upload multiple texts/images with just one template.
But the problem comes when I create a 2nd text/image template, the template by itself is created without a problem, but when I want to upload something using that template, well...
With the problem being in this part of the code:
Here are the full codes:
Creation of the templates:
Textos_DescripcionController.php (controller of the text template) :
public function store(Request $request){
$request->validate([
'nombre_texto' => ['required'],
'min' => ['required'],
'max' => ['required'],
]);
Textos_Descripcion::create($request->all());
$data_txt = DB::table('textos__descripcions')
->max('id');
$data_proyecto = $_POST['proyecto_id'];
//dd($data_proyecto);
Textos_Descripcion_Plantillas::insert(['proyecto_id' => $data_proyecto, 'texto_descripcion_id' => $data_txt]);
return redirect('/profile/' . auth()->user()->id);
}
TextosController.php (texts by themselves):
public function store(Request $request){
$plantilla_id = $_POST['id_descr'];
//Obtenemos ancho y alto de la plantilla
$min = DB::table('textos__descripcions')
->select('min')
->where('id' , '=', $plantilla_id)
->first();
$min_valor = $min->min;
$max = DB::table('textos__descripcions')
->select('max')
->where('id' , '=', $plantilla_id)
->first();
$max_valor = $max->max;
//ahora obtenemos los ancho y alto de la imagen
$largo = strlen($_POST["texto"]);
//ahora comparamos
if($min_valor > $largo || $max_valor < $largo){
echo "El texto no cumple con los estandares, la imagen debe ser desde " . $min->min . " hasta " . $max->max . "y tu texto tiene " . $largo . " caracteres ";
dd($largo);
return redirect('/profile/' . auth()->user()->id);
};
$paro = "Aqui toy";
echo "Succes, La imagen cumple con los estandares, la imagen debe ser desde " . $min->min . " hasta " . $max->max . "y tu texto tiene " . $largo . " caracteres ";
$request->validate([
'caption' => ['required'],
'texto' => ['required'],
'id_descr' => ['required'],
]);
//dd($paro);
Textos::create($request->all()); //
//Datos a tabla intermedia
$data_img = DB::table('textos__descripcion__plantillas')
->select('id')
->where('id' ,'=', $plantilla_id)
->first();
$data_img_valor = $data_img->id;
$id_proyecto = DB::table('proyectos')
->select('id')
->where('id','=', $data_img_valor)
->first();
$id_proyecto_valor = $id_proyecto->id; //I'm getting problems here
$id_txt = DB::table('textos')
->max('id');
Textos_Proyectos::insert(['proyectos_id' => $id_proyecto_valor , 'textos_id' => $id_txt]);
return redirect('/profile/' . auth()->user()->id);
}
I used a dd() right before the line of code that gives me problems, which gave a null. And to me this doesn't make sense, because it works with the 1st template, when I use the dd() I get the id of what I'm uploading:
Why is this happening?
I apologize is the question is too vague, if it lacks details please point it out
EDIT: I decided to change the first() to get() in the line that's throwing me problems, and I got an empty array
Related
This question already has answers here:
Constructor in PHP
(2 answers)
Closed 14 days ago.
I have the following code in 7.4 it worked for me now in 8.1 it doesn't work for me...
I corrected it by replacing foreach but I still have errors of
Undefined property: Plantilla::$mihtml
help please
I hope you can help me I don't know how to solve this problem
<?php
class Plantilla{
function Plantilla($template_file){
$this->tpl_file =$template_file ;
}
function asigna_variables($vars){
$this->vars= (empty($this->vars)) ? $vars : $this->vars . $vars;
}
function muestra(){
$this->template_file = $this->tpl_file;
$this->mihtml = $this->template_file;
$this->mihtml = str_replace ("'", "\'", $this->mihtml);
$this->mihtml = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . $\\1 . '", $this->mihtml);
reset ($this->vars);
foreach($this->vars as $key => $val) {
$$key = $val;
}
eval("\$this->mihtml = '$this->mihtml';");
reset ($this->vars);
foreach($this->vars as $key => $val)
{
unset($$key);
}
$this->mihtml=str_replace ("\'", "'", $this->mihtml);
return $this->mihtml;
//AQUI SI QUEREMOS USARDEFRENTE EN PARA MOSTTRAR SE DEBE CAMBIAR A ''ECHO'
}
}
$COD_RANDOM ='1234567899999999999999999999999999999999999';
$Contenido=new Plantilla('el codigo es {CODIGO_RANDOM}');//al Pasar como parametro Prueba, asumimos que en la carpeta plantillas existe un archivo de nombre Prueba.tpl
$Contenido->asigna_variables(array(
"CODIGO_RANDOM" => $COD_RANDOM //codigo generado
));
#$ContenidoString = $Contenido->muestra();//$ContenidoString contiene nuestra plantilla, ya con las variables asignadas, fácil no?
$mensajebody=$Contenido->muestra();
echo $mensajebody;
?> ```
espero me puedan ayudar por favor
You are giving $template when you create an $Contenido object.
new Plantilla('el codigo es {CODIGO_RANDOM}');
You mean it to be set as local property of class. But the construction function in PHP calls not by class name, but with special name __construct()
The code of class should start with the following
class Plantilla
{
function __construct($template_file) //<-- this function name changes
{
$this->tpl_file = $template_file;
}
}
Please, follow this manual: https://www.php.net/manual/en/language.oop5.decon.php
I have a table where I drag and drop, when I drop the row I want to update order values, it works but start updating from value 0 and I want start from 1.
Example before drag and drop:
After:
My code looks like here:
public function updateOrder(Request $request)
{
$queryParams = [];
$ids = $request->ids;
//el query será definido en su totalidad de forma manual
$query = 'UPDATE projects SET `order` = CASE id ';
//agregamos cada parámetro de orden y de id al array para respetar las convenciones de PDO
foreach ($ids as $order => $id) {
$query .= 'WHEN ? THEN ? ';
$queryParams[] = (int) $id;
$queryParams[] = (int) $order;
}
//por último agregamos los ids implicados en el update
$queryParams = array_merge($queryParams, $ids);
//generamos los ? necesarios para el array de ids en el query PDO
$whereInArray = array_fill(0, count($ids), '?');
$whereInString = implode(", ", $whereInArray);
//agregamos dicho string generado al query final
$query .= "END WHERE id IN ($whereInString)";
//realizamos el update
DB::update($query, $queryParams);
}
¿What I need to update in code?
Please try $queryParams[] = (int) $order+1;
I'm working with Codeigniter.
My function works, but I want to make a change and I can't figure how to do it.
My function is doing a read where "status_offre_id" = 1.
But I want it to read "status_offer_id" = 1 AND "status_offer_id" = 2
So far I tried this:
'status_offer_id' => (1 AND 2),
'status_offer_id' => 1,2,
('status_offer_id' => 1) AND ('status_offer_id' => 2),
and more
<?php
function showOffer(){
$idCompany = $_SESSION["company"]["id"];
$conditions = array(
'company_id' => $idCompany,
'status_offer_id' => 1,
);
$offer_published = $this->offer_model->lire("*", $conditions);
$data = array();
$data["offer"]=$offer_published;
$this->_layoutHaut();
$this->load->view('Company/offer_view', $data);
$this->_layoutBas();
}
?>
public function lire($selection = "*", $conditions = array(), $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
}
Try this :
$conditions = '(company_id = "' . $idCompany . '" AND status_offer_id IN (1, 2))';
Ur using CI which has active records, try to use them
$this->db->select("*")
->from($table)
->where('company_id', $company_id)
->where('status_offer_id', 1)
->or_where('status_offer_id',2)
$where = (select * from your_table where status_offer_id IN (1, 2));
$this->db->where('company_id', $company_id);
$this->db->where($where);
I will try to explain my case.
I would like to change the wpseo_title, wpseo_metakey, wpseo_metadesc, wpseo_opengraph_type, wpseo_opengraph_image, wpseo_title, and wpseo_opengraph_image_size on the "archive-page" of "custom post"
Because yoast plugin not translated meta tags inside "archive" post. And i need to translate all
I have this code:
function get_archive_seo() {
include 'seo_archive.php';
$tipoSel = get_post_type(get_the_ID());
if(is_post_type_archive( $tipoSel )){
foreach ($traduccionesArchive as $keyTipo => $tipo){
foreach ($tipo as $keyMeta => $palabra){
if($keyMeta == 'opengraph_type' || $keyMeta == 'opengraph_image_size') continue;
icl_register_string ('my-theme', $keyTipo." - ".$keyMeta, $palabra);
}
}
foreach ($traduccionesArchive[$tipoSel] as $key => $palabra){
add_filter( 'wpseo_'.$key, function($nombre) use ( $palabra, $tipoSel, $key ) {
if($key == 'opengraph_type' || $key == 'opengraph_image_size') return $palabra;
return icl_t('my-theme', $tipoSel." - ".$key, $palabra);
});
}
}
}
add_filter( 'wp_head', 'get_archive_seo');
And this is the "seo_archive.php":
$traduccionesArchive['hoteles']['title'] = 'Hotel, Vacaciones en Andalucia';
$traduccionesArchive['hoteles']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['hoteles']['metadesc'] = 'Mapa de Hotel en Andalucia, Costa del Sol, Costa de la Luz y Sierra de Grazalema. El lugar ideal para tus vacaciones.';
$traduccionesArchive['hoteles']['opengraph_type'] = 'object';
$traduccionesArchive['hoteles']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['hoteles']['opengraph_image_size'] = 100;
$traduccionesArchive['apartamentos']['title'] = 'Apartamentos de vacaciones Costa del Sol ';
$traduccionesArchive['apartamentos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['apartamentos']['metadesc'] = 'Mapa de localizacion de los Apartamentos Vacacionales de Hotel. Disfruta de tus vacaciones en familia en la Costa del Sol.';
$traduccionesArchive['apartamentos']['opengraph_type'] = 'object';
$traduccionesArchive['apartamentos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['apartamentos']['opengraph_image_size'] = 100;
$traduccionesArchive['destinos']['title'] = 'Mapa de localizacion de Hotel, Andalucia';
$traduccionesArchive['destinos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['destinos']['metadesc'] = 'Mapa de Hoteles en Andalucia, en los destinos vacacionales de Costa del Sol, Costa de la Luz y Sierra de Grazalema Andalucia.';
$traduccionesArchive['destinos']['opengraph_type'] = 'object';
$traduccionesArchive['destinos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['destinos']['opengraph_image_size'] = 100;
$traduccionesArchive['ofertas']['title'] = 'Ofertas Hotel Costa del Sol, Costa de la Luz ';
$traduccionesArchive['ofertas']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['ofertas']['metadesc'] = 'Ahorra en tus vacaciones con las ofertas en nuestros hoteles de la Costa del Sol, Costa de la Luz y Andalucia.';
$traduccionesArchive['ofertas']['opengraph_type'] = 'object';
$traduccionesArchive['ofertas']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['ofertas']['opengraph_image_size'] = 100;
But now, it not works, but in the past works fine, the filter is form module yoast SEO https://yoast.com/wordpress/plugins/seo/
Y tried with this Wordpress: How to return value when use add_filter?
I'm a little confused because this:
add_filter( 'wpseo_title', function(){return 'foo';}
Works outside the get_archive_seo functions, but not works inside function.
Can anybody help me?
You can use like this, this may help to you.
function title_function_name($title) {
$title = "Your title write here";
return $title;
}
add_filter('wp_title', 'title_function_name', 15);
if (!has_filter('wpseo_title'))
add_filter('wpseo_title', 'title_function_name', 15);
I want to insert 2 times but I have routes that redirects each other, I make the first Insertion and then redirijo to another path to insert again. Would have to put begin-> transanction ()
This well done ?. regards
I first made the first Insertion, in the route
$app->post("/orders/insert", function() use($app)
{
$empleado = ORM::for_table('empleado')->select('id')->where('usuario_idusuario',$_SESSION['user_id'])->find_one();
$cliente = 'proveedor';
if(!$empleado)
{
$app->flash('error','La cuenta de usuario tiene que estar asociado a un empleado registrado en la base de datos');
$app->redirect($app->urlFor('cartList'));
}
try
{
$insertOrder = ORM::for_table('pedido')->create();
$insertOrder->fechapedido = date('Y/m/d');
$insertOrder->estado = 1;
$insertOrder->empleado_id = $empleado->id;
$insertOrder->proveedor_id = $_SESSION['idproveedor'];
$insertOrder->save();
$app->redirect("/lineorder/insert/$cliente");
}
catch(PDOException $e)
{
$app->flash('error','Ha ocurrido un error en la base de datos, no se ha insertado ningún pedido'.$e->getMessage());
$app->redirect($app->urlFor('cartList'));
}
});
After I go to the route that redirect and realized:
$app->map('/lineorder/insert/:cliente', function($cliente) use($app)
{
if(!isset($_SESSION['cart-items']))
{
$app->redirect($app->urlFor('create-order'));
$app->flash('error','No tienes carritos');
}
//Si existe la variable de sesion
else
{
if(count($_SESSION['cart-items'])>0)
{
$idpedido = ORM::for_table('pedido')->count();
foreach($_SESSION['cart-items'] as $id => $cantidad)
{
$producto = ORM::for_table('producto')->select_many('id','precioVenta','precioProveedor')->where('id',$id)->find_one();
$preciounidad = ($cliente==='proveedor') ? $producto->precioProveedor : $producto->precioVenta;
$lineorder_insert = ORM::for_table('lineapedido')->create();
$lineorder_insert->pedido_idpedido = $idpedido;
$lineorder_insert->producto_idproducto =$producto->id;
$lineorder_insert->cantidad = $cantidad;
$lineorder_insert->preciounidad = $preciounidad;
$lineorder_insert->save();
//Actualizo cantidad en la table productos
$cantidad_stock =$producto->cantidad_stock;
$cantidad_stock+=$cantidad;
$update_amount = ORM::for_table('producto')->find_one($id);
$update_amount->set('cantidad_stock',$cantidad_stock);
$update_amount->save();
$app->flash('success',"pedido {$idpedido} creado correctamente");
$app->redirect($app->urlFor('orderList'));
}
}
}
})->via('GET','POST');
I need begin->transaction()
Would you be well done?